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