问题描述
有两个 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
如果应用于您问题中的样本数据 - 输出为