我有一张包含以下数据的表格。
**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个月记录。如果特定月份的DB中不存在任何优先级类型,则显示零而不是实际计数。
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
答案 0 :(得分:0)
您可以使用left join
生成行。然后使用group 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;
完成查询:
validator['name'](false)
请注意,这使用子查询来获取优先级和月份。您可以使用其他方法(例如引用表或显式列出值)。