Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 在一个查询中获取所有非';t在另一个小组中_Sql_Amazon Redshift_Intersection - Fatal编程技术网

Sql 在一个查询中获取所有非';t在另一个小组中

Sql 在一个查询中获取所有非';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

考虑到我使用的是红移,我如何获取查询的计数,该查询要求:

给定表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
(
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的,我想红移中也会使用
除外
。@一匹没有名字的马谢谢我编辑了我的答案