BigQuery SQL:如何在比较日期范围内的两个表时查找缺失值?
BigQuery SQL: How to find missing Values on comparing two tables over date range?
有两个Bigquery表如下所示:
Table 1:
Store Report_Date
11 2021-03-03
12 2021-03-03
11 2021-04-14
13 2021-04-14
Table 2:
Store
11
12
13
场景:
与 Table 2 家商店相比,每个日期必须找到 Table 1 家缺失的商店。
预期输出:
在比较时列出每个日期的每个缺失商店。
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
使用日历table方法:
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
如果应用于您问题中的示例数据 - 输出为
有两个Bigquery表如下所示:
Table 1:
Store Report_Date
11 2021-03-03
12 2021-03-03
11 2021-04-14
13 2021-04-14
Table 2:
Store
11
12
13
场景: 与 Table 2 家商店相比,每个日期必须找到 Table 1 家缺失的商店。
预期输出: 在比较时列出每个日期的每个缺失商店。
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
使用日历table方法:
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
如果应用于您问题中的示例数据 - 输出为