Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL sum by year report, looking for an elegant solution

I have a table with 3 columns: ItemCode, Quantity and DocDate. I would like to create the following report in a more "elegant" way:

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)

I'm pretty sure there's a better, more efficient way to write this but I can't come up with the right syntax. Any ideas?

like image 939
Urik Avatar asked Dec 26 '22 13:12

Urik


1 Answers

You can try this:

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
like image 72
Ivan Golović Avatar answered Jan 15 '23 17:01

Ivan Golović