小编典典

SQL按年汇总报告,寻找一种优雅的解决方案

sql

我有一个包含3列的表格:ItemCode,Quantity和DocDate。我想以更“优雅”的方式创建以下报告:

SELECT T0.ItemCode, 
       (SELECT SUM(QUANTITY) FROM MyTable T1 WHERE YEAR(T0.DocDate) = 2011 AND T0.ItemCode = T1.ItemCode) AS '2011',
       (SELECT SUM(QUANTITY) FROM MyTable T1 WHERE YEAR(T0.DocDate) = 2012 AND T0.ItemCode = T1.ItemCode) AS '2012'
FROM MyTable T0
GROUP BY T0.ItemCode, YEAR(T0.DocDate)

我很确定有一种更好,更有效的方式编写此代码,但是我无法提出正确的语法。有任何想法吗?


阅读 191

收藏
2021-03-17

共1个答案

小编典典

您可以尝试以下方法:

SELECT  T0.ItemCode, 
        SUM(CASE WHEN YEAR(T0.DocDate) = 2011 THEN QUANTITY ELSE 0 END) AS '2011',
        SUM(CASE WHEN YEAR(T0.DocDate) = 2012 THEN QUANTITY ELSE 0 END) AS '2012'
FROM    MyTable T0
GROUP BY 
        T0.ItemCode
2021-03-17