以下是我的表数据
time_stamp Name
01-Mar-14 a
02-Mar-14 b
02-Mar-14 c
01-May-14 d
02-May-14 e
01-Jun-14 f
需要输出:
(3,0,2,1) (Month wise count with 0 if month doesn't exist)
我创建了以下查询:
select
listagg(count(1),',') within group (order by EXTRACT(month FROM time_stamp))
from ps_bqueues_host
where time_stamp BETWEEN TO_DATE('01-Mar-14', 'DD-Mon-YY') and
TO_DATE('01-Jun-14', 'DD-Mon-YY') GROUP BY EXTRACT(month FROM time_stamp)
这给了我输出:
(3,2,1) (Month of Apr with 0 is not there).
请建议如何在所有月份分组。
感谢。
答案 0 :(得分:1)
您应该将此原始表格与表格一起加入给定期间内的所有月份。如果是在一年之内,那么we need 1,2,3,...12 sequence。
select
listagg(count(Name),',') within
group (order by m.rn)
from
(SELECT * FROM ps_bqueues_host
where time_stamp
BETWEEN TO_DATE('01-Mar-14', 'DD-Mon-YY')
and TO_DATE('01-Jun-14', 'DD-Mon-YY')
)
RIGHT JOIN
(SELECT LEVEL rn FROM dual CONNECT BY LEVEL <= 12) m
ON m.rn=EXTRACT(month FROM time_stamp)
WHERE m.rn BETWEEN EXTRACT(month FROM TO_DATE('01-Mar-14', 'DD-Mon-YY'))
AND EXTRACT(month FROM TO_DATE('01-Jun-14', 'DD-Mon-YY'))
GROUP BY m.rn