Sql 在一个查询中获取所有非';t在另一个小组中
考虑到我使用的是红移,我如何获取查询的计数,该查询要求: 给定表A和表B,给出表A中不在表B中的分组的所有值计数 因此,如果表A和B看起来像: 表ASql 在一个查询中获取所有非';t在另一个小组中,sql,amazon-redshift,intersection,Sql,Amazon Redshift,Intersection,考虑到我使用的是红移,我如何获取查询的计数,该查询要求: 给定表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 使用除和子查询之外的 with a as ( selec
Id | Value
==========
1 | "A"
1 | "B"
2 | "C"
表B:
Id | Value
==========
1 | "A"
1 | "D"
2 | "C"
我想:
Id | Count
==========
1 | 1
2 | 0
使用除和子查询之外的
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
使用<代码>和子查询除外
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
您可以使用左连接
和分组方式
:
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;
您可以使用左连接
和分组方式
:
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;
对不起,我不明白您的逻辑对不起,我不明白您的逻辑减去是Oracle特有的。SQL标准使用的是除外
——因为红移是基于Postgres的,所以我假设它在红移中也会是除外
。@没有名字的马谢谢我编辑了我的答案减去
,这是Oracle特有的。SQL标准使用的是除外
——因为红移是基于Postgres的,我想红移中也会使用除外
。@一匹没有名字的马谢谢我编辑了我的答案