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.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Concat unique values from different rows

Author  Topic 

nirnir
Starting Member

10 Posts

Posted - 2014-02-06 : 11:20:05
In table1 I have a key field(not unique) and data
In table2 I have one row per table1 key
I need to concat into table2.uniqeValues field all table1.data of the same key .
Attached table1 values and the desired table2 values .

What is the most efficient way to update table2.uniqeValues

Table1
Key,data
A,val1
A,val1
A,val1
A,val2
A,val3
B,val1
B,val2
B,val2


Table2 should be

Key,uniqeValues
A, "val1,val2,val3"
B,"val1,val2"

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2014-02-06 : 16:47:39
[code]SELECT t.Key,
STUFF(f.Data, 1, 1, '') AS UniqueValues
FROM (
SELECT Key
FROM dbo.Table1
GROUP BY Key
) AS t
CROSS APPLY (
SELECT DISTINCT ',' + CAST(Data AS VARCHAR(12))
FROM dbo.Table AS w
WHERE w.Key = t.Key
ORDER BY ',' + CAST(Data AS VARCHAR(12))
FOR XML PATH(''),
TYPE
) AS f(Data);[/code]


Microsoft SQL Server MVP, MCT, MCSE, MCSA, MCP, MCITP, MCTS, MCDBA
Go to Top of Page

nirnir
Starting Member

10 Posts

Posted - 2014-02-07 : 06:50:44
Thanks
Go to Top of Page
   

- Advertisement -