我正在尝试与销售差异进行逐年比较。我下面有两个SQL语句可提取所需的正确数据。我想我应该在这里使用CASE表达式?如果是这样,我一直在看的示例使用CASE WHEN YEAR(DATEFIELD)= DATE THEN X ELSE X END)?令我感到困惑的是,我们的财政年度始于12月,因此数据的第一个月来自不同的年份。非常感谢这里的任何指导。
当前会计年度数据
SELECT B.COMPANY, SUM(C.PRICE_BEFORE_TAX) AS CURRENTFY
FROM ARINVOICE A
LEFT OUTER JOIN ARCUSTO B ON A.ARCUSTO_ID = B.ID
LEFT OUTER JOIN V_ARINVOICE_DETAIL C ON A.ID = C.ARINVOICE_ID
WHERE TRUNC(A.INVOICE_DATE) >= TO_DATE('12/01/2018' , 'MM/DD/YYYY')
AND TRUNC(A.INVOICE_DATE) <= TO_DATE('11/30/2019' , 'MM/DD/YYYY')
GROUP BY B.COMPANY
ORDER BY CURRENTFY DESC)
上一财政年度数据
(SELECT B.COMPANY, SUM(C.PRICE_BEFORE_TAX) AS LASTFY
FROM ARINVOICE A
LEFT OUTER JOIN ARCUSTO B ON A.ARCUSTO_ID = B.ID
LEFT OUTER JOIN V_ARINVOICE_DETAIL C ON A.ID = C.ARINVOICE_ID
WHERE TRUNC(A.INVOICE_DATE) >= TO_DATE('12/01/2017' , 'MM/DD/YYYY')
AND TRUNC(A.INVOICE_DATE) <= (SYSDATE-365)
GROUP BY B.COMPANY
ORDER BY LASTFY DESC))
所需结果
SELECT B.COMPANY, CURRENTFY, LASTFY, (((CURRENTFY-LASTFY)/CURRENTFY)*100) AS SALESVARIANCE
编辑---------------------
感谢Gordon,我正在使用以下内容
SELECT c.COMPANY,
SUM(CASE WHEN id.INVOICE_DATE >= DATE '2018-12-01' AND id.INVOICE_DATE <= DATE '2019-12-01'
THEN id.PRICE_BEFORE_TAX
END) AS CURRENTFY,
SUM(CASE WHEN id.INVOICE_DATE >= DATE '2017-12-01' AND id.INVOICE_DATE <= (SYSDATE-365)
THEN id.PRICE_BEFORE_TAX
END) AS LASTFY,
ROUND(((SUM(CASE WHEN id.INVOICE_DATE >= DATE '2018-12-01' AND id.INVOICE_DATE <= DATE '2019-12-01'
THEN id.PRICE_BEFORE_TAX
END) -
SUM(CASE WHEN id.INVOICE_DATE >= DATE '2017-12-01' AND id.INVOICE_DATE <= (SYSDATE-365)
THEN id.PRICE_BEFORE_TAX
END))/(SUM(CASE WHEN id.INVOICE_DATE >= DATE '2018-12-01' AND id.INVOICE_DATE <= DATE '2019-12-01'
THEN id.PRICE_BEFORE_TAX
END)))*100 , 2) AS SALESVARIANCE
FROM ARINVOICE i LEFT JOIN
ARCUSTO c
ON i.ARCUSTO_ID = c.ID LEFT JOIN
V_ARINVOICE_DETAIL id
ON i.ID = id.ARINVOICE_ID
GROUP BY c.COMPANY
ORDER BY CURRENTFY DESC
答案 0 :(得分:2)
仅使用条件聚合:
SELECT c.COMPANY,
SUM(CASE WHEN id.INVOICE_DATE >= DATE '2018-12-01' AND id.INVOICE_DATE < DATE '2019-12-01'
THEN id.PRICE_BEFORE_TAX
END) AS CURRENTFY,
SUM(CASE WHEN id.INVOICE_DATE >= DATE '2017-12-01' AND id.INVOICE_DATE < DATE '2018-12-01'
THEN id.PRICE_BEFORE_TAX
END) AS LASTFY
FROM ARINVOICE i LEFT JOIN
ARCUSTO c
ON i.ARCUSTO_ID = c.ID LEFT JOIN
V_ARINVOICE_DETAIL id
ON i.ID = id.ARINVOICE_ID
GROUP BY c.COMPANY
ORDER BY CURRENTFY DESC;
注意:
DATE
关键字用作日期常数。WHERE
中的时间比较,因此添加更多会计年度更加容易。显然,您仍然可以过滤最近两年的值。