我是SQL Server的新手,曾经尝试过一些互联网上建议的技术,例如使用临时变量,XML路径COALESCE等,但是所有这些都不满足我的要求。
COALESCE
我正在使用Toad for SQL Server 5.5版创建SQL脚本,而我用来查询数据库服务器的帐户仅具有READ访问权限。因此不能使用CREATE VIEW我相信的声明。
CREATE VIEW
表名: Customer
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
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;