SQL 声明总结了缺失的员工认证

SQL Statement summarize missing employee certifications

我正在尝试创建一个关于我无法修改的表格的报告,我不确定这是否可行。

使用下面的脚本,我试图得到一个查询结果:

--Certification | Employee     | Has Certification
--CPR           | Santa Clause | Yes
--CPR           | Rudolph      | No

CREATE TABLE [dbo].[Certification]([Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NOT NULL,
CONSTRAINT [PK_Certification] PRIMARY KEY CLUSTERED ([Id] ASC));

CREATE TABLE [dbo].[Employee]([Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NOT NULL,
CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED ([Id] ASC));

CREATE TABLE [dbo].[EmployeeCertification]([Id] [int] IDENTITY(1,1) NOT NULL,
[CertificationID] [int] NOT NULL,
[EmployeeID] [int] NOT NULL,
CONSTRAINT [PK_EmployeeCertification] PRIMARY KEY CLUSTERED ([Id] ASC));

ALTER TABLE [dbo].[EmployeeCertification] WITH CHECK ADD CONSTRAINT
[FK_EmployeeCertification_Certification] FOREIGN KEY([CertificationID])
REFERENCES [dbo].[Certification] ([Id])

ALTER TABLE [dbo].[EmployeeCertification] CHECK CONSTRAINT
[FK_EmployeeCertification_Certification]

ALTER TABLE [dbo].[EmployeeCertification] WITH CHECK ADD  CONSTRAINT
[FK_EmployeeCertification_Employee] FOREIGN KEY([EmployeeID])
REFERENCES [dbo].[Employee] ([Id])

ALTER TABLE [dbo].[EmployeeCertification] CHECK CONSTRAINT
[FK_EmployeeCertification_Employee]

INSERT INTO Certification (Name) VALUES ('CPR');
INSERT INTO Employee (Name) VALUES ('Santa Clause'),('Rudolph');
INSERT INTO EmployeeCertification (CertificationID,EmployeeID) VALUES(1,1);

您可以cross join employees 和 certifications 来生成所有可能的组合,然后使用子查询检查桥中是否存在每个元组 table:

select c.name as certification, e.name as employee,
    case when exists (
        select 1 
        from employeecertification ec 
        where ec.employeeid = e.id and ec.certificationid = c.id
    ) then 'Yes' else 'No' end as has_certification
from employee e
cross join certification c

这也可以用 left join:

select c.name as certification, e.name as employee,
    case ec.id is null then 'No' else 'Yes' end as has_certification
from employee e
cross join certification c
left join employeecertification ec on ec.employeeid = e.id and ec.certificationid = c.id