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?
This type of data transformation is known as a
PIVOT
. There are several ways that you can perform this operation. You can use thePIVOT
function or you can use an aggregate function with aCASE
statement:Static Pivot Version: This is where you hard-code all of the values into the query
See SQL Fiddle with Demo
Case with Aggregate:
See SQL Fiddle with Demo
Dynamic Pivot: The previous two versions will work great is you have a known number of
year
values to transform, but it you have an unknown number then you can use dynamic sql:See SQL Fiddle with Demo
All three versions will produce the same result:
You can try this: