总和字段取决于日期的月份和年份分组

时间:2019-09-04 06:55:14

标签: sql oracle

我有一张桌子。

tbl_work:

ACCOUNT        TOTAL        LAST_UPDATE_DATE
============================================== 
21157         3779444      2018-01-02 00:00:00
21157         7200000      2018-01-04 00:00:00
21157         131275053    2018-02-01 00:00:00
21157         6646465      2018-02-02 00:00:00
21157         36268657     2018-03-01 00:00:00
21157         3622400      2018-03-02 00:00:00
21157         17201657     2018-04-04 00:00:00
21157         3549999      2018-04-07 00:00:00
21157         14364000     2018-05-02 00:00:00
21157         77726800     2018-05-04 00:00:00

这将按完整的DateTime分组,包括日期,小时和分钟。我希望仅按月份和年份MM / YYYY进行分组,并对其进行一些求和。

到目前为止,我已经尝试过:

SELECT ACCOUNT, SUM(total) AS TOTAL, TRUNC(created_date) AS LAST_UPDATE_DATE
FROM rkap_realisasi
WHERE account = '21157' 
AND TRUNC(created_date) BETWEEN TO_DATE('1/1/2018', 'MM/DD/YYYY') AND TO_DATE('1/1/2019','MM/DD/YYYY')
GROUP BY account, EXTRACT(YEAR_MONTH FROM(TRUNC(created_date)))

但似乎效果不佳。

我的预期输出是:

ACCOUNT        TOTAL        LAST_UPDATE_DATE
============================================= 
21157         10979444      2018-01-04 00:00:00
21157         137921518     2018-02-01 00:00:00
21157         39891057      2018-03-02 00:00:00
21157         20751656      2018-04-07 00:00:00
21157         92090800      2018-05-04 00:00:00 

任何有思想的建议都会受到赞赏。

谢谢。

3 个答案:

答案 0 :(得分:1)

您只需要使用以下查询按月和年分组:

SELECT ACCOUNT, SUM(total) AS TOTAL, max(created_date) AS LAST_UPDATE_DATE
FROM rkap_realisasi
WHERE account = '21157' 
AND TRUNC(created_date) BETWEEN TO_DATE('1/1/2018', 'MM/DD/YYYY') AND TO_DATE('1/1/2019','MM/DD/YYYY')
GROUP BY account, TRUNC(created_date, 'month')

干杯!

答案 1 :(得分:0)

使用max()作为日期

SELECT ACCOUNT, SUM(total) AS TOTAL, max(TRUNC(created_date)) AS LAST_UPDATE_DATE
FROM rkap_realisasi
WHERE account = '21157' 
AND TRUNC(created_date) BETWEEN TO_DATE('1/1/2018', 'MM/DD/YYYY') AND TO_DATE('1/1/2019','MM/DD/YYYY')
GROUP BY account,EXTRACT(YEAR_MONTH FROM(TRUNC(created_date)))

答案 2 :(得分:0)

您可以将TO_CHAR()函数与'YYYYMM'参数结合使用:

SELECT account,
       TO_CHAR(created_date,'YYYYMM'),
       SUM(total) AS TOTAL,
       MAX(TRUNC(created_date)) AS LAST_UPDATE_DATE
  FROM rkap_realisasi
 WHERE account = '21157'
   AND TRUNC(created_date) BETWEEN DATE'2018-01-01' AND DATE'2019-01-01'
 GROUP BY account, TO_CHAR(created_date,'YYYYMM')