簡體   English   中英

顯示記錄,即使數據庫中不存在

[英]Display record even if it doesn't exist in DB

我有一張下面的數據表。

**Priority**    **Mydate**              **ID**
Critical       2018/01/20               1090
High           2018/01/27               1091
High           2018/01/18               1092
High           2018/01/24               1093
Low            2017/09/28               1083

要求是獲取所有優先級類型(嚴重,高,中和低)及其數量的最近12個月的記錄。 如果特定月份數據庫中不存在任何優先級類型,則顯示零而不是實際計數。

SELECT TO_CHAR(Mydate, 'MM/YYYY') AS Mydate, PRIORITY, count(*)
FROM MYTABLE
WHERE Mydate >= add_months(trunc(sysdate, 'month'), - 12)
GROUP BY TO_CHAR(Mydate, 'MM/YYYY'), PRIORITY
ORDER BY TO_CHAR(Mydate, 'MM/YYYY') ASC, PRIORITY ASC;

通過上面的查詢,我只能做到這一點:

Mydate      PRIORITY        Count
---------------------------------
01/2018     High            3
01/2018     Critical        1
09/2017     Low             1

預期結果是:

Mydate      PRIORITY        Count
---------------------------------
01/2018     Critical        1
01/2018     High            3
01/2018     Medium          0
01/2018     Low             0
09/2017     Critical        0
09/2017     High            0
09/2017     Medium          0
09/2017     Low             1

您可以使用cross join生成行。 然后使用left joingroup by完成查詢:

select p.priority, ym.yyyymm, count(*) as cnt
from (select distinct priority
      from t
     ) p cross join
     (select distinct to_char(my_date, 'YYYY-MM') as yyyymm
      from t
      Mydate >= add_months(trunc(sysdate, 'month'), - 12)
    ) ym left join
    (select t.*, to_char(my_date, 'YYYY-MM') as yyyymm
      from t
     ) t
     on t.priority = p.priority and t.yyyymm = ym.yyyymm
group by p.priority, ym.yyyymm;

請注意,這使用子查詢來獲取優先級和月份。 您可以使用其他方法(例如參考表或顯式列出值)。

暫無
暫無

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

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