如何按月包括所有月份?

时间:2017-05-29 13:15:36

标签: oracle group-by calendar date-arithmetic

我按月分组我的表

  SELECT TO_CHAR (created, 'YYYY-MM') AS operation, COUNT (id)
    FROM user_info
   WHERE created IS NOT NULL
GROUP BY ROLLUP (TO_CHAR (created, 'YYYY-MM'))

2015-04 1
2015-06 10
2015-08 22
2015-09 8
2015-10 13
2015-12 5
2016-01 25
2016-02 37
2016-03 24
2016-04 1
2016-05 1
2016-06 2
2016-08 2
2016-09 7
2016-10 103
2016-11 5
2016-12 2
2017-04 14
2017-05 2
        284

但记录并未涵盖所有月份 我希望输出包含所有月份,输出中显示缺少的输出,默认值为:

2017-01 ...
2017-02 ...
2017-03 ZERO
2017-04 ZERO
2017-05 ...

1 个答案:

答案 0 :(得分:1)

Oracle有a good array of date manipulation functions。这个问题的两个相关问题是

  • MONTHS_BETWEEN()计算两个日期之间的月数
  • ADD_MONTHS()以指定的月数递增日期

我们可以将这些函数组合在一起生成一个表格,其中包含表格记录所涵盖的所有月份。然后我们使用外连接有条件地将USER_INFO中的记录连接到该日历。如果没有匹配count(id)的记录将为零。

with cte as (
  select max(trunc(created, 'MM')) as max_dt
         , min(trunc(created, 'MM')) as min_dt
  from user_info
  )
 , cal as (
    select add_months(min_dt, (level-1)) as mth
    from cte
    connect by level <= months_between(max_dt, min_dt) + 1
)
select to_char(cal.mth, 'YYYY-MM') as operation
       , count(id)
from  cal
     left outer join user_info
   on trunc(user_info.created, 'mm') = cal.mth
group by rollup (cal.mth)
order by 1
/