计数(*)根据时间段按月查询需要添加零值,而不是不添加数据



数据库是Oracle 12C标准版。

我想按月计算一段时间内的某些值。查询有效,但如果一个月没有数据,我想添加零而不是没有数据。

select  count(*) count_c,  to_char(close_date, 'YYYY-MM') yr_month 
from 
tbl
where  
close_date between add_months(trunc(sysdate, 'mm'), -6) 
and 
trunc(sysdate, 'mm') - 1   
group by to_char(close_date, 'YYYY-MM') order by yr_month;
Result:
count_c   yr_month
353       2020-01
236       2020-02
266       2020-04
327       2020-05
369       2020-06

请注意,没有三月的数据,但我希望查询返回的三月计数为零。

Desired Output
count_c   yr_month
353       2020-01
236       2020-02
0         2020-03
266       2020-04
327       2020-05
369       2020-06

感谢

您需要日期生成器,然后左键联接查询到生成器。例如:

select *
from 
(
select 
add_months(
date'2020-01-01' /* < start date */
,level - 1 /* number of months to add */
) dt
from dual 
connect by level<=months_between(
date'2020-05-01' /* < end date */
,date'2020-01-01' /* < start date */
)+1
) gen
/* left join (
{your_query here}
) data
on gen.dt = data.dt
*/

最新更新