oracle中带表达式的累计和

时间:2018-07-05 18:46:29

标签: sql oracle select sum

我正在尝试通过以下查询获取累计金额:

SELECT to_char(INVC_DT, 'MON-YYYY') AS MONTH 
       ,SUM(INVC_AMT)
       /*, here I need a third column with the cumulative sum of the second column*/
FROM T_INVC_INFO I INNER JOIN T_TASK_INFO T ON I.TASK_ID = T.TASK_ID
WHERE T.CNTRCT_ID = #session.user.cntrct_id#
GROUP BY to_char(INVC_DT, 'MON-YYYY')
ORDER BY MONTH DESC

2 个答案:

答案 0 :(得分:1)

我将这个查询与另一个查询一起包装,并使用sum的窗口变体:

SELECT   month, sum_month, SUM(sum_month) OVER (ORDER BY month DESC)
FROM     (SELECT     TO_CHAR(invc_dt, 'MON-YYYY') AS month,
                     SUM(invc_amt) AS sum_month
          FROM       t_invc_info i
          INNER JOIN t_task_info t ON i.task_id = t.task_id
          WHERE      t.cntrct_id = #session.user.cntrct_id#
          GROUP BY   TO_CHAR(invc_dt, 'MON-YYYY'))
ORDER BY month DESC

答案 1 :(得分:1)

我会做:

SELECT to_char(INVC_DT, 'MON-YYYY') AS MONTH,
       SUM(INVC_AMT),
       SUM(SUM(INVC_AMT)) OVER (ORDER BY MIN(INVC_DT))
FROM T_INVC_INFO I INNER JOIN T_TASK_INFO T ON I.TASK_ID = T.TASK_ID
WHERE T.CNTRCT_ID = #session.user.cntrct_id#
GROUP BY to_char(INVC_DT, 'MON-YYYY')
ORDER BY MONTH DESC;

请注意,ORDER BY子句按日期而不是按字母顺序按月。

您可能还希望ORDER BY MIN(INVC_DT)作为最终订单。