Merge data in two row into one [duplicate]

2020-03-31 03:20发布

Possible Duplicate:
Concatenate row values T-SQL

I'm new to SQL Server and had tried few techniques that suggested from internet like using temp variable, XML path, COALESCE and etc but all doesn't meet my requirement somehow.

I'm using Toad for SQL Server version 5.5 to create SQL script and the account I used to query DB server only got READ access. Hence can't use CREATE VIEW statement I believe.

Table Name : Customer

ServerName  Country  contact
----------  -------  -------------
srv1        SG       srv1_contact1
srv1        SG       srv1_contact2
srv1        SG       srv1_contact3
srv2        HK       srv2_contact1
srv2        HK       srv2_contact2
srv3        JP       srv3_contact1
srv3        JP       srv3_contact2
srv3        JP       srv3_contact3
srv4        KR       srv4_contact1

Expected output:

ServerName  Country  contact
----------  -------  -------------------------------------------
srv1        SG       srv1_contact1; srv1_contact2; srv1_contact3
srv2        HK       srv2_contact1; srv2_contact2
srv3        JP       srv3_contact1; srv3_contact2; srv3_contact3
srv4        KR       srv4_contact1

1条回答
放荡不羁爱自由
2楼-- · 2020-03-31 03:57
SELECT ServerName, Country, contact = STUFF((SELECT '; ' 
    + ic.contact FROM dbo.Customer AS ic
  WHERE ic.ServerName = c.ServerName AND ic.Country = c.Country
  FOR XML PATH(''), TYPE).value('.','nvarchar(max)'), 1, 2, '')
FROM dbo.Customer AS c
GROUP BY ServerName, Country
ORDER BY ServerName;
查看更多
登录 后发表回答