使用一个组来获取一个查询中没有的所有值

时间:2019-07-22 17:20:05

标签: sql amazon-redshift intersection

鉴于我正在使用Redshift,如何查询以下内容的计数:

给出表A和表B,为我提供表A中该表中所有不在表B中的值的所有计数;

因此,如果表A和B看起来像:

表A

Id | Value
==========
 1 | "A"
 1 | "B"
 2 | "C"

表B:

Id | Value
==========
 1 | "A"
 1 | "D"
 2 | "C"

我想要:

Id | Count
==========
 1 |  1
 2 |  0

2 个答案:

答案 0 :(得分:1)

使用except和子查询

with a as
(
select 1 as id, 'A' as v
union all
select 1,'B'
union all
select 2,'C'
),b as
(
select 1 as id, 'A' as v
union all
select 1,'D'
union all
select 2,'C'
), c as
(
select id,v from a except select id,v from b
)
select id,sum ( (select count(*) from c where c.id=a.id and c.v=a.v))
from a group by id

输出

id  cnt
1   1
2   0

online demo which will work in redshift

答案 1 :(得分:1)

您可以使用left joingroup by

select a.id, sum( (b.id is null)::int )
from a left join
     b
     on a.id = b.id and a.value = b.value
group by a.id;