Count(*) 按月按时间段查询需要加零值而不是没有数据
Count(*) Query based on a time period by month need to add zero value instead of no data
数据库为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
请注意,没有 3 月的数据,但我希望查询到 return 3 月,计数为零。
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
*/
数据库为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
请注意,没有 3 月的数据,但我希望查询到 return 3 月,计数为零。
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
*/