首页 > 解决方案 > 在 SQL 中查找丢失/删除的行

问题描述

我有一个表,它存储来自源的完整提取。我想跟踪完整提取中缺少的 id 并将其存储在目标表(所需输出)格式中。你能提供关于sql的建议吗?

源表

id  source_extract_date 

1   1/1/2001  
2   1/1/2001  
3   1/1/2001
4   1/1/2001

1   2/1/2001   
3   2/1/2001
4   2/1/2001

1   3/1/2001   
3   3/1/2001
4   3/1/2001

1   4/1/2001   
3   4/1/2001
2   4/1/2001

1   5/1/2001   
3   5/1/2001
2   5/1/2001

目标表(期望的输出)

id    effective_from    is_deleted
1       1/1/2001            false
2       1/1/2001            false
3       1/1/2001            false
4       1/1/2001            false
2       2/1/2001            true
4       4/1/2001            true
2       4/1/2001            false

标签: sql

解决方案


SELECT possibles.*, case when st.id is null then 'True' Else 'False' END As IsDeleted
FROM (
    select ids.id, dates.sources_extract_date 
    from 
    (select distinct id from [source_table]) ids
    cross join 
    (select distinct source_extract_date from [source_table]) dates
) possibles
LEFT JOIN [source_table] st ON st.id = possibles.id and st.source_extract_date = possibles.source_extract_date 

推荐阅读