开发者

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.


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜