如何获得包含不存在值的结果集?

How to get a result set containing the absence of a value?

场景:有一个包含四列的 table。 District_Number、District_name、Data_Collection_Week,注册人数。每周我们都会获得数据,但有时我们不会。 任务:我的主管要我生成一个查询,让我们知道哪些学区在给定的一周内没有提交。 下面是我尝试过的,但是对于那些一周未提交的,我无法得到 NULL 值。

SELECT DISTINCT DistrictNumber, DistrictName, DataCollectionWeek
into #test4
FROM EDW_REQUESTS.INSTRUCTION_DELIVERY_ENROLLMENT_2021
order by DistrictNumber, DataCollectionWeek asc


select DISTINCT DataCollectionWeek
into #test5
from EDW_REQUESTS.INSTRUCTION_DELIVERY_ENROLLMENT_2021
order by DataCollectionWeek


select b.DistrictNumber, b.DistrictName, b.DataCollectionWeek
from #test5 a left outer join #test4 b on (a.DataCollectionWeek = b.DataCollectionWeek)
order by b.DistrictNumber, b.DataCollectionWeek asc

一个选项使用两个 select distinct 子查询的 cross join 来生成所有可能的地区和周组合,然后 not exists 识别那些 table:

select d.districtnumber, w.datacollectionweek
from (select distinct districtnumber from edw_requests.instruction_delivery_enrollment_2021) d
cross join (select distinct datacollectionweek from edw_requests.instruction_delivery_enrollment_2021) w
where not exists (
    select 1
    from edw_requests.instruction_delivery_enrollment_2021 i
    where i.districtnumber = d.districtnumber and i.datacollectionweek = w.datacollectionweek
)   

如果您有引用 table 来存储地区和周,这会更简单(并且效率更高):然后您将直接使用它们而不是 select distinct 子查询。