将数据合并为一行

时间:2012-06-27 16:17:10

标签: sql sql-server sql-server-2008 tsql

  

可能重复:
  Concatenate row values 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

预期产出:

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 个答案:

答案 0 :(得分: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;