鉴于我正在使用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
答案 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
答案 1 :(得分:1)
您可以使用left join
和group 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;