【问题标题】:Display record even if it doesn't exist in DB即使数据库中不存在也显示记录
【发布时间】:2018-08-14 07:49:32
【问题描述】:

我有一个包含以下数据的表格。

**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

【问题讨论】:

标签: sql oracle count


【解决方案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;

请注意,这使用子查询来获取优先级和月份。您可以使用其他方法(例如参考表或显式列出值)。

【讨论】:

    猜你喜欢
    • 2012-07-12
    • 1970-01-01
    • 1970-01-01
    • 2015-04-19
    • 2021-08-30
    • 2013-11-17
    • 2012-11-17
    • 1970-01-01
    • 2016-01-06
    相关资源
    最近更新 更多