I have Two tables 1. #SetValuesTable
2. #labelTempTab
Data in #SetValuesTable
look like this :
MNUM la1 la2 la3 la4 PropertyType
12 1 0 2 s
13 4 0 5 7 p
Data in #labelTempTab
look like this :
RowNum Label Title PropertyType
1 la1 Agent1 s
2 la2 Agent2 s
3 la3 Agent3 s
4 la1 Agent1 p
5 la2 Agent2 p
6 la3 Agent3 p
7 la4 Agent4 p
I need the result table like this :
MNUM LabelName LabelValue PropertyType
12 la1 1 s
12 la2 0 s
12 la3 2 s
13 la1 4 p
13 la2 0 p
13 la3 5 p
13 la4 7 p
Query :
SELECT MNUM, LabelName , LabelValue FROM #SetValuesTable
CROSS APPLY ( VALUES '
stuff(( SELECT ',('''+ replace(C.label,'''','"') + ''',' + quotename(C.label) + ')' FROM #labelTempTab c group by label FOR xml path('')), 1, 1, '')
) AS UPTab (Label , LabelValue);
The above query will result in :
MNUM LabelName LabelValue
12 la1 1
12 la2 0
12 la3 2
13 la1 4
13 la2 0
13 la3 5
13 la4 7
Can some body help me to get the rest of the columns also.
Note : I tried to unpiovt the tabel using UNPIVOT but the performance is not so good. With cross apply the performance is really good.