簡體   English   中英

Oracle查詢獲取月份數據,並提供0月份不可用

[英]Oracle query to get month wise data and give 0 for month not available

以下是我的表數據

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

請建議如何在所有月份分組。

謝謝。

您應該將此原始表格與表格一起加入給定期間內的所有月份。 如果它在一年內,那么我們需要1,2,3,... 12序列

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

SQLFiddle演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM