开发者

SQL query to format the result

开发者 https://www.devze.com 2023-02-10 22:27 出处:网络
I have data in following format: 24Asian Fish 24Atlantis 24Bakery 24Bistro 24Bon Appetite开发者_开发问答

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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消