Oracle SQL-按每天,每周和每月对数据进行汇总和分组。 (缺少日期,星期和月份)

时间:2019-09-15 07:13:52

标签: sql oracle

我需要按每日,每周和每月获取交易组的总金额。 我尝试过的结果给了我预期的结果,但是如果在特定时期内没有交易,则没有给出日期,星期或月份。

Daily

SELECT to_char(tran_timestamp, 'YYYY/MM/DD') FROM TRANSACTIONS
WHERE
TRAN_STATUS = 'SUCCESS' AND
tran_timestamp  >= TO_DATE('2019/07/01', 'yyyy/mm/dd')
AND tran_timestamp <= TO_DATE('2019/09/30','yyyy/mm/dd')
GROUP BY to_char(TRAN_TIMESTAMP, 'YYYY/MM/DD')
ORDER BY to_char(TRAN_TIMESTAMP, 'YYYY/MM/DD');

Weekly

SELECT to_char(tran_timestamp, 'YYYY/MM/W') FROM TRANSACTIONS
WHERE
TRAN_STATUS= 'SUCCESS' AND
tran_timestamp  >= TO_DATE('2019/07/01', 'yyyy/mm/dd')
AND tran_timestamp <= TO_DATE('2019/09/30','yyyy/mm/dd')
GROUP BY to_char(TRAN_TIMESTAMP, 'YYYY/MONTH/W')
ORDER BY to_char(TRAN_TIMESTAMP, 'YYYY/MONTH/W');

Monthly

SELECT to_char(tran_timestamp, 'YYYY/MM/MM') FROM TRANSACTIONS
WHERE
TRAN_STATUS = 'SUCCESS' AND
tran_timestamp  >= TO_DATE('2019/07/01', 'yyyy/mm/dd')
AND tran_timestamp <= TO_DATE('2019/09/30','yyyy/mm/dd')
GROUP BY to_char(TRAN_TIMESTAMP, 'YYYY/MONTH/MM')
ORDER BY to_char(TRAN_TIMESTAMP, 'YYYY/MONTH/MM');

例如: 每月结果

Date     Total amt
2019/09  100
2019/07  500

但是我需要像这样的结果:

Date     Total amt
2019/09  100
2019/08  0
2019/07  500

1 个答案:

答案 0 :(得分:1)

您需要在开始日期和结束日期之间生成all dates,并将其与查询结果结合起来。

以下查询将给出每日总金额。如果要获取每周和每月的结果,则需要更改group byorder byselect clause

select all_dates.d as tran_timestamp, 
       sum(your_query.amt) as total_amt
 from
    (select date '2019-07-01' + level - 1 as d
       from dual
     connect by level <= (date '2019-09-30' - date '2019-07-01' ) + 1) all_dates 
Left join
    (SELECT trunc(tran_timestamp) as tran_timestamp , amt
       FROM TRANSACTIONS
      WHERE TRAN_STATUS = 'SUCCESS' 
        AND tran_timestamp  >= TO_DATE('2019/07/01', 'yyyy/mm/dd')
        AND tran_timestamp <= TO_DATE('2019/09/30','yyyy/mm/dd')) your_query
On (all_dates.d = tran_timestamp)
Group by all_dates.d
order by all_dates.d;

干杯!