I need a little help.
I have table with structure as follows:
table1
Year Id1 ID2 ID3
2001 1 20 Null
2001 2 400 Null
2002 1 100 Null
2002 2 50 Null
2002 3 null 60
2002 4 88 Null
2005 3 Null 45
2001 1 20 Null
2001 2 400 Null
2002 1 100 Null
2002 2 50 Null
2002 3 null 60
2002 4 88 Null
2005 3 Null 45
Each year can have upto 4 rows with Id1 as (1,2,3,4). If ID2 has value then ID3 will be null and vice versa
I want my output as
Key1 Val1 Val2 Val3 Val4
2001 20 400 Null Null
2002 100 50 60 88
2005 null null 45 null
2001 20 400 Null Null
2002 100 50 60 88
2005 null null 45 null
I have designed a query
SELECT Year,
(CASE WHEN Id1 = 1 THEN (CASE WHEN Id2 IS Not NULL THEN Id2 ELSE Id3 END ) ELSE NULL END) AS Val1,
(CASE WHEN Id1 = 2 THEN (CASE WHEN Id2 IS Not NULL THEN Id2 ELSE Id3 END ) ELSE NULL END) AS Val2,
(CASE WHEN Id1 = 3 THEN (CASE WHEN Id2 IS Not NULL THEN Id2 ELSE Id3 END ) ELSE NULL END) AS Val3,
(CASE WHEN Id1 = 4 THEN (CASE WHEN Id2 IS Not NULL THEN Id2 ELSE Id3 END ) ELSE NULL END)) AS Val4
FROM Sales
GROUP BY Year
(CASE WHEN Id1 = 1 THEN (CASE WHEN Id2 IS Not NULL THEN Id2 ELSE Id3 END ) ELSE NULL END) AS Val1,
(CASE WHEN Id1 = 2 THEN (CASE WHEN Id2 IS Not NULL THEN Id2 ELSE Id3 END ) ELSE NULL END) AS Val2,
(CASE WHEN Id1 = 3 THEN (CASE WHEN Id2 IS Not NULL THEN Id2 ELSE Id3 END ) ELSE NULL END) AS Val3,
(CASE WHEN Id1 = 4 THEN (CASE WHEN Id2 IS Not NULL THEN Id2 ELSE Id3 END ) ELSE NULL END)) AS Val4
FROM Sales
GROUP BY Year
WIll This work to get my desired output. If not Any suggestions/help will be appreciated