【问题标题】:Find the average of ids in a month求一个月内的平均 id
【发布时间】:2021-01-30 12:15:10
【问题描述】:

我可以计算一个月内的 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| YEAR | OVER_ALL_COUNT| AVG
 1| 2019 | 712           | 59.33
 2| 2019 | 20936849      | 161185684.6
 3| 2019 | 14255773      | 2177532.2

但是,我想修改它以获取一个月的所有 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,而 jan 的平均 id=2 计数为 1611。

【问题讨论】:

    标签: sql oracle datetime count


    【解决方案1】:

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

    select id, to_char(event_day, 'Mon') event_month, sum(cnt) overall_count, avg(cnt) average_count
    from (
        select id, trunc(event_date) event_day, count(*) cnt
        from daily 
        where event_date >= date '2019-01-01' and event_date < date '2019-01-31'
        group by id, trunc(event_date)
    ) t
    group by id, to_char(event_month, 'Mon')
    

    【讨论】:

      【解决方案2】:

      这回答了问题的原始版本。

      你可以使用last_day():

      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')
      

      【讨论】:

      • 感谢您的回答!我意识到我没有正确地提出问题我已经更新了问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-14
      • 2016-06-08
      • 1970-01-01
      • 2017-03-25
      • 1970-01-01
      相关资源
      最近更新 更多