Possible Duplicate:
dynamic sql pivot in sql server
I have a table called Col_values and Col_ID is an Identity field the data looks like:
Val_ID Col_ID Value
76951792 3 Closed
76951791 3 Closed
76951790 25 Open
76951789 25 Closed
76951792 1 US
76951791 1 Canada
and another table called Et_Col and the data looks like:
Col_ID Col_Name D_ID
3 Status 1
25 Status 2
1 Country 1
I want the output as:
Val_ID Status Country
76951792 Closed US
76951791 Closed Canada
76951790 Open Null
76951789 Closed Null
So I wrote a cursor to get the output and the cursor returns the statement like:
Select val_ID
,max(case when Col_ID = 3 then Value end) as Status
,max(case when Col_ID = 25 then Value end) as Status
,max(CASE WHEN Col_ID = 1 THEN VALUE END ) AS Country
From Col_values
Group by Val_ID
this gives me output as:
Val_ID Status Status Country
76951792 Closed Null US
76951791 Closed Null Canada
76951789 Null Closed Null
76951790 Null Open Null
How can I fix This?