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) F

我有一个包含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)

我很确定有更好,更有效的方式来编写这个,但我无法想出正确的语法.有任何想法吗?

解决方法

你可以试试这个:

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

关于作者: dawei

【声明】:石家庄站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

为您推荐