2

我正在加入 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;
4

2 回答 2

1

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

在 Microsoft SQL Server 2005 中模拟 group_concat MySQL 函数?

于 2013-04-19T11:57:21.120 回答
1

你可以使用东西

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

在此处输入图像描述

SQL小提琴

于 2013-04-19T13:19:45.290 回答