我有这段代码:
SELECT
SUM(SUM(INCOME))OVER(ORDER BY TO_DATE(TO_CHAR(PAYMENT_DATE, 'MM/YYYY'), 'MM/YYYY'))
AS CUMULATIVE_INCOME,
SUM(SUM(EXPENSE))OVER(ORDER BY TO_DATE(TO_CHAR(PAYMENT_DATE, 'MM/YYYY'), 'MM/YYYY'))
AS CUMULATIVE_EXPENSE,
SUM(INCOME) AS TOTAL_MONTH_INCOME,
SUM(EXPENSE) AS TOTAL_MONTH_EXPENSE,
TO_CHAR(PAYMENT_DATE, 'MM/YYYY') AS MONTH
FROM
V_CFW_CASH_FLOW
GROUP BY TO_CHAR(PAYMENT_DATE, 'MM/YYYY')
ORDER BY TO_DATE(MONTH, 'MM/YYYY') ASC
我想要的是另一个列,其中包含减去累计收入的结果 - 累计费用。
我尝试了下一个但没有工作:
SUM(SUM(INCOME))OVER(ORDER BY TO_DATE(TO_CHAR(PAYMENT_DATE, 'MM/YYYY'), 'MM/YYYY'))
- SUM(SUM(EXPENSE))OVER(ORDER BY TO_DATE(TO_CHAR(PAYMENT_DATE, 'MM/YYYY'), 'MM/YYYY'))
AS NET,
答案 0 :(得分:1)
使用公用表表达式:
WITH cteSUMS AS (SELECT TO_CHAR(PAYMENT_DATE, 'MM/YYYY') AS MONTH,
SUM(SUM(INCOME))
OVER (ORDER BY TO_DATE(TO_CHAR(PAYMENT_DATE, 'MM/YYYY'), 'MM/YYYY'))
AS CUMULATIVE_INCOME,
SUM(SUM(EXPENSE))
OVER (ORDER BY TO_DATE(TO_CHAR(PAYMENT_DATE, 'MM/YYYY'), 'MM/YYYY'))
AS CUMULATIVE_EXPENSE,
SUM(INCOME) AS TOTAL_MONTH_INCOME,
SUM(EXPENSE) AS TOTAL_MONTH_EXPENSE
FROM V_CFW_CASH_FLOW
GROUP BY TO_CHAR(PAYMENT_DATE, 'MM/YYYY'))
SELECT MONTH,
CUMULATIVE_INCOME,
CUMULATIVE_EXPENSE,
TOTAL_MONTH_INCOME,
TOTAL_MONTH_EXPENSE,
TOTAL_MONTH_INCOME - TOTAL_MONTH_EXPENSE AS NET
FROM cteSUMS
ORDER BY TO_DATE(MONTH, 'MM/YYYY') ASC
如果需要,可以使用两个公用表表达式使其更清晰:
WITH cteDATA AS (SELECT TO_CHAR(PAYMENT_DATE, 'MM/YYYY') AS MONTH,
INCOME,
EXPENSE
FROM V_CFW_CASH_FLOW),
cteSUMS AS (SELECT MONTH,
SUM(SUM(INCOME))
OVER (ORDER BY TO_DATE(MONTH, 'MM/YYYY'))
AS CUMULATIVE_INCOME,
SUM(SUM(EXPENSE))
OVER (ORDER BY TO_DATE(MONTH, 'MM/YYYY'))
AS CUMULATIVE_EXPENSE,
SUM(INCOME) AS TOTAL_MONTH_INCOME,
SUM(EXPENSE) AS TOTAL_MONTH_EXPENSE
FROM cteDATA
GROUP BY MONTH)
SELECT MONTH,
CUMULATIVE_INCOME,
CUMULATIVE_EXPENSE,
TOTAL_MONTH_INCOME,
TOTAL_MONTH_EXPENSE,
TOTAL_MONTH_INCOME - TOTAL_MONTH_EXPENSE AS NET
FROM cteSUMS
ORDER BY TO_DATE(MONTH, 'MM/YYYY') ASC
祝你好运。