我不知道我的查询有什么问题。我只是在我的查询中输入'MM'来获得每月结果。但是当我运行它时,它会在365天内给出每日结果,而不是每月结果。请帮帮我。
这是我的疑问:
SELECT 'Data'
|| ',' || TO_CHAR(d.dtime_day, 'MM/dd/yyyy')
|| ',' || NVL(o.cnt_opened, 0) --as cnt_opened
|| ',' || NVL(c.cnt_closed, 0) --as cnt_closed
FROM owner_dwh.dc_date d
LEFT JOIN (
SELECT
TRUNC(t.create_time, 'MM') AS report_date,
count(*) AS cnt_opened
FROM app_account.otrs_ticket t
WHERE t.create_time BETWEEN SYSDATE - 365 AND SYSDATE
GROUP BY TRUNC(t.create_time, 'MM')
) o ON d.dtime_day = o.report_date
LEFT JOIN (
SELECT
TRUNC(t.close_time, 'MM') AS report_date,
count(*) AS cnt_closed
FROM app_account.otrs_ticket t
WHERE t.close_time BETWEEN SYSDATE - 365 AND SYSDATE
GROUP BY TRUNC(t.close_time, 'MM')
) c ON d.dtime_day = c.report_date
WHERE d.dtime_day BETWEEN SYSDATE - 365 AND SYSDATE
ORDER BY d.dtime_day;
结果:
Data,01/25/2013,0,0
Data,01/26/2013,0,0
Data,01/27/2013,0,0
Data,01/28/2013,0,0
Data,01/29/2013,0,0
Data,01/30/2013,0,0
答案 0 :(得分:1)
您对DC_DATE
的初始查询是获取过去365天内的每个日期。如果你只运行那部分:
SELECT 'Data'
||','||TO_CHAR(D.DTIME_DAY,'MM/dd/yyyy')
FROM OWNER_DWH.DC_DATE d
WHERE d.DTIME_DAY BETWEEN SYSDATE -365 AND SYSDATE
ORDER BY D.DTIME_DAY;
...你希望得到365行返回。
您在外部加入的子查询只会返回每个月第一天的摘要计数。因此,当您加入时,您将在每个月的第一天获得实际值(可能为零),但在每个其他日期始终为零。您可以通过调整where
子句来避免这种情况,例如:
WHERE d.DTIME_DAY BETWEEN SYSDATE -365 AND SYSDATE
AND d.DTIME_DAY = TRUNC(s.DTIME_DAY, 'MM')
这只会显示每月的第一天,如果子查询中没有匹配的数据,外连接仍将显示零值的日期。