可以将表的单个列分组并连接到SQL Server中的单个单元格中吗?

时间:2013-04-19 11:54:13

标签: sql sql-server

我正在加入SQL Server中的许多表,我需要返回所有可能的经理的电子邮件地址。可能的经理由设施所在的国家决定。

理想情况下,我只希望为每个设施返回一行,并将所有管理员的电子邮件地址放在一个用分号分隔的单个单元格中。

我尝试了Pivot和COALESCE,但是我无法产生预期的结果,有谁知道如何做到这一点? 或者我是以完全错误的方式解决这个问题?

CREATE TABLE Facility(  
    [FacilityId] [int] NOT NULL,
    [Address] [varchar](256)
    [CountryCode] [char](2) NOT NULL,
)

CREATE TABLE ManagementDivision(    
    [ManagementDivisionId] [int] NOT NULL,
    [Name] [varchar](256)
    [CountryCode] [char](2) NOT NULL,
)

CREATE TABLE Manager(
    [ManagerID] [numeric](8, 0) NULL,
    [ManagementDivisionId] [int] NOT NULL
)

CREATE TABLE Employee(
    [EmployeeId] [numeric](8, 0) NOT NULL,
    [mail] [varchar](1000) NULL
)  

示例数据

insert into Facility (FacilityId, Address, CountryCode) values(1, '123 Fake St' 'US')
insert into Facility (FacilityId, Address, CountryCode) values(2, '789 Forgery Rd' 'US')
insert into Facility (FacilityId, Address, CountryCode) values(3, '567 Bogus Bld' 'AU')

insert into ManagementDivision (ManagementDivisionId, Name, CountryCode) values(1, 'East Coast USA' 'US')
insert into ManagementDivision (ManagementDivisionId, Name, CountryCode) values(2, 'West Coast USA' 'US')
insert into ManagementDivision (ManagementDivisionId, Name, CountryCode) values(3, 'Central USA' 'US')
insert into ManagementDivision (ManagementDivisionId, Name, CountryCode) values(4, 'Australia' 'AU')

insert into Manager (ManagerId, ManagementDivisionId) values(1, 1)
insert into Manager (ManagerId, ManagementDivisionId) values(1, 2)
insert into Manager (ManagerId, ManagementDivisionId) values(2, 3)
insert into Manager (ManagerId, ManagementDivisionId) values(3, 4)

insert into Employee (EmployeeId, mail) values(1, 'manager1@somedomain.com')
insert into Employee (EmployeeId, mail) values(2, 'manager2@somedomain.com')
insert into Employee (EmployeeId, mail) values(3, 'manager3@somedomain.com')

期望的结果

FacilityId  Address         CountryCode ManagerEmail
1           123 Fake St     US          manager1@somedomain.com; manager2@somedomain.com;
2           789 Forgery Rd  US          manager1@somedomain.com; manager2@somedomain.com;
3           567 Bogus Bld   AU          manager3@somedomain.com;

2 个答案:

答案 0 :(得分:1)

此操作在MySQL中称为group_concat。这是关于如何在SQL Server中执行此操作的SO项目。

Simulating group_concat MySQL function in Microsoft SQL Server 2005?

答案 1 :(得分:1)

您可以使用 Stuff

select 
F.FacilityId,
F.[Address],
F.CountryCode,
STUFF(
(SELECT Distinct ', '+E.mail
from Facility F1
inner join ManagementDivision MD on F1.CountryCode=MD.CountryCode
inner join Manager M on MD.ManagementDivisionId=M.ManagementDivisionId
INNER JOIN Employee E ON M.ManagerID=E.EmployeeId
WHERE F1.Address=F.Address
AND F1.CountryCode=F.CountryCode
AND F1.FacilityId=F.FacilityId
FOR XML PATH (''))
  ,1,2,'') AS Email
from Facility F

enter image description here

<强> SQL Fiddle