【问题标题】:How to find missing data in table Sql如何在表 Sql 中查找缺失的数据
【发布时间】:2020-10-28 21:15:49
【问题描述】:

这类似于How to find missing data rows using SQL?How to find missing rows (dates) in a mysql table?,但有点复杂,所以我碰壁了。

我有一个带有注明主键的数据表:

country_id (PK)
product_id (PK)
history_date (PK)
amount

我有一个包含所有产品的产品表、一个国家/地区表和一个包含所有有效日期的日历表。

我想查找所有缺少产品的国家、日期和产品,并带有以下皱纹: 我只关心至少有一种产品的国家/地区条目的日期(即,如果该国家/地区当天没有任何东西,我不需要找到它) - 所以,根据定义,有一个条目在我关心的每个国家和日期的历史记录表。

我知道这将涉及一些连接,可能是交叉连接,但我在查找缺失数据时遇到了障碍。

我试过这个(很确定它不会起作用):

SELECT h.history_date, h.product_id, h.country_id, h.amount
FROM products p
LEFT JOIN history h ON (p.product_id = h.product_id)
WHERE h.product_id IS NULL

没有喜悦。

我也试过这个:

WITH allData AS (SELECT h1.country_id, p.product_id, h1.history_date
FROM products p 
CROSS JOIN (SELECT DISTINCT country_id, history_date FROM history) h1)
SELECT f.history_date, f.product_id, f.country_id
FROM allData f
LEFT OUTER JOIN history h ON (f.country_id = h.country_id AND f.history_date = h.history_date AND f.product_id = h.product_id)
WHERE h.product_id IS NULL 
   AND h.country_id IS NOT NULL 
   AND h.history_date IS NOT null

也没有运气。 CTE 确实在每个有数据的日期都为我提供了所有产品,但其余的都没有返回任何数据。

【问题讨论】:

    标签: sql sql-server sql-server-2012


    【解决方案1】:

    我只关心一个国家/地区有条目的日期 至少一种产品(即如果该国当天没有任何产品,我 不用找)

    所以我们关心这个组合:

    from    (select distinct country_id, history_date from history) country_date
    cross join products p
    

    那么就是检查存在性的问题了:

    select *
    from    (select distinct country_id, history_date from history) country_date
    cross join products p
    where not exists (select null
                      from history h
                      where country_date.country_id   = h.country_id
                       and  country_date.history_date = h.history_date
                       and  p.product_id              = h.product_id
                     ) 
    

    【讨论】:

    • 所以我很接近,但没有雪茄。太好了,谢谢!
    • 要更正您的版本,您只需查看针对外部连接表使用的过滤器。 AND h.country_id IS NOT NULL 只有在所有外连接条件上都有匹配的行时才会为真。
    猜你喜欢
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多