一个查询中多个值的计算计数

时间:2020-06-03 16:20:39

标签: sql postgresql count

我有一张这样的答案表:

ID ItemID Answer 
1   1      yes
2   1      no
3   1      yes
4   1      yes
5   2      no
6   2      yes
7   3      yes

我希望能够提供一个ItemId的数组,并为该数组中的每个number of yes answers - number of no answers计算一个ItemID

我可以对单个项目执行以下操作:

SELECT (SELECT count(ID) FROM table WHERE ItemID= <id> AND Answer = 'Yes') - (SELECT count(ID) FROM table WHERE ItemID= <id> AND Answer = 'No') AS difference

但是我怎样才能使其适应一个查询中的多个ID?

在输入为[1,2]的情况下,我的预期输出类似于

ItemID Difference 
  1      2
  2      0

2 个答案:

答案 0 :(得分:2)

只需使用条件聚合:

select itemid,
       count(*) filter (where answer = 'yes') as num_yes,
       count(*) filter (where answer = 'no') as num_no
from t
group by itemid;

如果您想将其限制为特定项目,则可以包含where itemid in (1, 2)(或类似内容)。

答案 1 :(得分:0)

您可以使用case语句和聚合通过以下提到的查询来实现:

尝试

select itemid "ItemID", sum(case when answer = 'yes' then 1 else -1 end) "Difference"
from example 
where itemid in (1,2) --condition can be removed if required for all IDs
group by itemid

Demo