如何解决BigQuery SQL:如何在日期范围内比较两个表时找到缺失值?
有两个 Bigquery 表,如下所示:
表 1:
Store Report_Date
11 2021-03-03
12 2021-03-03
11 2021-04-14
13 2021-04-14
表 2:
Store
11
12
13
场景: 与表 2 的 Stores 比较,必须找到每个日期缺少的表 1 的 Stores。
预期输出: 在比较时列出每个日期的每个缺失的商店。
MissingStore Report_Date
13 2021-03-03
12 2021-04-14
尝试查询: 但是这个查询没有显示相应的 Report_Date,而是显示“null”。
WITH
tab1 AS (
SELECT
disTINCT Store,Report_Date
FROM
tab1
)
SELECT
disTINCT tab2.Store,tab1.Report_Date
FROM
tab2
LEFT JOIN
tab1
ON
tab1.Store = tab2.Store
WHERE
tab1.Store IS NULL
解决方法
使用日历表方法:
SELECT s.Store AS MissingStore,d.Report_Date
FROM (SELECT DISTINCT Store FROM tab1) s
CROSS JOIN (SELECT DISTINCT Report_Date FROM tab1) d
INNER JOIN tab2 t2
ON s.Store = t2.Store
LEFT JOIN tab1 t1
ON t1.Store = s.Store AND t1.Report_Date = d.Report_Date
WHERE t1.Store IS NULL;
,
考虑以下方法
select a.Store MissingStore,b.Report_Date
from table2 a
cross join (select distinct Report_Date from table1) b
left join table1 c
using(Store,Report_Date)
where c.Report_Date is null
如果应用于您问题中的样本数据 - 输出为
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。