Om.
Om.

Reputation: 113

SQL query to format the result

I have data in following format:

24  Asian Fish
24  Atlantis
24  Bakery
24  Bistro
24  Bon Appetite
24  Camo
24  Fish Bones
25  Black
38  Black
38  Burgundy
38  Dark Green
38  Navy
38  Red

Could you please suggest what query can be used to format it in following way:

24       Asian Fish|Atlantis|Bakery|Bistro|Bon Appetite|Camo|Fish Bones
25       Black
38       Black|Burgundy|Dark Green|Navy|Red

This is for SQL Server 2005.

Upvotes: 2

Views: 353

Answers (1)

marc_s
marc_s

Reputation: 754230

Since you didn't specify what database system you're using - here's one way to do it in SQL Server (2005 and up):

SELECT 
    DISTINCT ID,
    STUFF((SELECT '|' + t2.Fishy
     FROM dbo.YourTable t2
     WHERE t2.ID = t.ID
     FOR XML PATH('')), 1, 1, '') 'Fishes'
FROM dbo.YourTable t

This will produce the output:

ID  Fishes
24  Asian Fish|Atlantis|Bakery|Bistro|Bon Appetite|Camo|Fish Bones
25  Black
38  Black|Burgundy|Dark Green|Navy|Red

Upvotes: 5

Related Questions