Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 查找一个月内ID的平均值_Sql_Oracle_Datetime_Count - Fatal编程技术网

Sql 查找一个月内ID的平均值

Sql 查找一个月内ID的平均值,sql,oracle,datetime,count,Sql,Oracle,Datetime,Count,我可以计算一个月内ID的数量,然后在12个月内求和。我也用这个代码得到了平均值 select id, to_char(event_month, 'yyyy') event_year, sum(cnt) overall_count, avg(cnt) average_count from ( select id, trunc(event_date, 'month') event_month, count(*) cnt from daily where event_date

我可以计算一个月内ID的数量,然后在12个月内求和。我也用这个代码得到了平均值

select id, to_char(event_month, 'yyyy') event_year, sum(cnt) overall_count, avg(cnt) average_count
from (
    select id, trunc(event_date, 'month') event_month, count(*) cnt
    from daily 
    where event_date >= date '2019-01-01' and event_date < '2019-01-31'
    group by id, trunc(event_date, 'month')
) t
group by id, to_char(event_month, 'yyyy')
但是,我想修改它以获得一个月的全部id计数以及每个月的平均id计数。预期结果是:

ID| MONTH | OVER_ALL_COUNT| AVG
 1| Jan   | 152            | 10.3
 2| Jan   | 15000          | 1611
 3| Jan   | 14255          | 2177
 1| Feb   | 4300           | 113
 2| Feb   | 9700           | 782
 3| Feb   | 1900           | 97

其中,对于id=1,1月份总共有152个id计数,每天的平均id计数为10.3。对于id=2,一月的计数为15000,一月的平均id=2计数为1611。

这回答了问题的原始版本

您可以使用“最后一天”:


您只需要将子查询上的截断更改为按天而不是按月截断,然后按月而不是按年截断外部查询

选择id、事件日、“周一”事件月、累计总计数、平均计数 从…起 选择id,truncevent\u date事件\u day,count*cnt 每日 其中,事件日期>=日期“2019-01-01”和事件日期<日期“2019-01-31” 按id、TrunceEvent\u日期分组 T 按id分组,至月“周一”
谢谢你的回答!我意识到我没有正确地提出问题,我已经更新了问题。
ID| MONTH | OVER_ALL_COUNT| AVG
 1| Jan   | 152            | 10.3
 2| Jan   | 15000          | 1611
 3| Jan   | 14255          | 2177
 1| Feb   | 4300           | 113
 2| Feb   | 9700           | 782
 3| Feb   | 1900           | 97
select id, to_char(event_month, 'yyyy') event_year, sum(cnt) as overall_count,
       avg(cnt) as average_count,
       extract(day from last_day(min(event_month)) as days_in_month,
       sum(cnt) / extract(day from last_day(min(event_month)) as avg_days_in_month
from (select id, trunc(event_date, 'month') as event_month, count(*) as cnt
      from daily 
      where event_date >= date '2019-01-01' and
            event_date < date '2020-01-01'
      group by id, trunc(event_date, 'month')
     ) t
group by id, to_char(event_month, 'yyyy')