【问题标题】:How to get a result set containing the absence of a value?如何获得包含不存在值的结果集?
【发布时间】:2020-11-04 14:41:58
【问题描述】:

场景:有一个有四列的表。 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

【问题讨论】:

标签: sql sql-server tsql subquery distinct


【解决方案1】:

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

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
)   

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

【讨论】:

  • @Hakka-4 如果您正在为每年创建一个表,正如instruction_delivery_enrollment_2021 所暗示的那样,那么这将在新的一年/表的开始时解开,因为在表来提供“缺失”的地区。您将需要:(不好的选择)从前一年获取它们或(好的选择),正如 GMB 建议的那样,创建一个提供所有地区的 Districts 表,理想情况下,从 instruction_delivery_enrollment_2021 引用它(和随后几年)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-01
  • 2011-07-24
相关资源
最近更新 更多