我试图只在 1 个表中获取记录,即在 A 但不在 B case1 中:
select count(distinct t.col1),count(distinct t.col2)
from `table1` e
right join
(
select distinct col1,col2
from `table2_*`
where _table_suffix between '20180101' and '20181231'
)t
on e.col1=t.col1
where date(timestamp_seconds(ts))>='2018-01-01'
and e.col1 is null
;
案例2:
select count(distinct col1)
from `table2_*`
where _table_suffix between '20180101' and '20181231'
and col1 not in (
select distinct col1 from `table1`
where date(timestamp_seconds(ts))>='2018-01-01'
)
在这 2 个代码中,case2 起作用,而 case1 给出 0 作为输出。我还尝试将案例 1 作为左连接与反转的表,但结果是相同的 0 行。我是 Big Query 和标准 sql 版本的新手,不确定为什么会发生这种情况。
如果使用NOT IN
你不能让NULL作为“列表”的价值
SELECT count(DISTINCT t.col1)
FROM `table2_ * ` AS t
WHERE t._table_suffix BETWEEN '20180101' AND '20181231'
AND col1 NOT IN (
SELECT DISTINCT e.col1
FROM `table1` AS e
WHERE DATE (timestamp_seconds(e.ts)) >= '2018-01-01'
AND e.col1 IS NOT NULL
);
我个人更喜欢使用NOT EXISTS
:
SELECT count(DISTINCT t.col1)
FROM `table2_ * ` AS t
WHERE t._table_suffix BETWEEN '20180101' AND '20181231'
AND NOT EXISTS (
SELECT NULL
FROM `table1` AS e
WHERE DATE (timestamp_seconds(e.ts)) >= '2018-01-01'
AND e.col1 = t.col1
);
注意,这里的子查询 select 子句不需要返回任何值,所以select null
或select 1
或select *
都有效。使用exits
ornot exists
时,重要的是子查询的 from & where 子句。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句