将数据合并为一行

use*_*134 1 sql t-sql sql-server sql-server-2008

可能重复:
连接行值T-SQL

我是SQL Server的新手,并尝试过几种从互联网上建议的技术,比如使用临时变量,XML路径COALESCE等,但都不能满足我的要求.

我正在使用Toad for SQL Server 5.5来创建SQL脚本,而我用来查询DB服务器的帐户只能获得READ访问权限.因此不能使用CREATE VIEW我相信的声明.

表名: 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
Run Code Online (Sandbox Code Playgroud)

预期产量:

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
Run Code Online (Sandbox Code Playgroud)

Aar*_*and 7

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;
Run Code Online (Sandbox Code Playgroud)