Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
i have below data Id val--------------1 val11 val22 val32 val4i wanted to achieve as below Id val------------------1 val1 val22 val3 val4So i found below query. But its cost is very high and when applied for real time data its taking time.Is there any optimised way to achieve it in sql server ?CREATE TABLE #temptable(Id INT, val nvarchar(16)) INSERT INTO #temptable VALUES (1, 'val1')INSERT INTO #temptable VALUES(1, 'val2')INSERT INTO #temptable VALUES(2, 'val3')INSERT INTO #temptable VALUES(2, 'val4') SELECT m1.Id, STUFF(( SELECT ' ' +m2.val FROM #temptable m2 WHERE m2.Id = m1.Id ORDER BY val FOR XML PATH('')),1,1 ,'') AS val FROM #temptable m1 GROUP BY m1.Id ;
Ifor
Aged Yak Warrior
700 Posts
Posted - 2013-12-05 : 06:41:25
If there are always two Vals per Id, you could try a PIVOTSomething like:
SELECT Id, [1] + ' ' + [2] AS ValFROM( SELECT Id, Val, ROW_NUMBER() OVER (PARTITION BY Id ORDER BY Val) AS rn FROM #temptable) AS SPIVOT( MAX(VAL) FOR rn IN ([1], [2])) AS P;
Kristen
Test
22859 Posts
Posted - 2013-12-05 : 07:04:20
This any use?http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=81254