I have a table as
Date Item Quantity
20170101 Mango 5
20170101 Orange 6
20170102 Mango 7
20170102 Orange 8
I want below output
Date Mango Orange
20170101 5 6
20170102 7 8
for this i used below sql query
SELECT
Date,
SUM(case when Item='Mango' then Quantity else 0 end) AS Mango,
SUM(case when Item='Orange' then Quantity else 0 end) AS Orange
FROM orderTable
GROUP BY date
but this is kind of hard coding for Mango and Orange. What if I need new item in orderTable. Can any one suggest me how can I make this query dynamic. So that if I add new item it automatically create new coulmn having item name as name and it will have 0 value under column against date when order not placed for that item.
like
Date Item Quantity
20170101 Mango 5
20170101 Orange 6
20170102 Mango 7
20170102 Orange 8
20170102 Cherry 9
then output should be as ...
Date Mango Orange Cherry
20170101 5 6 0
20170102 7 8 9
OutPut
Try this :
dynamic sql :
result :
If you do this it will give you result that you want
Result:
Reference (code pic not shown but you can access it if you view source the page) : http://sqlmag.com/t-sql/pivoting-dynamic-way