1

I have a table of answers like this:

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

I'd like to be able to provide an array of ItemId and compute the number of yes answers - number of no answers for each ItemID in the array.

I can do this for an individual item like this:

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

but how can I adapt this to work for multiple ids in one query?

My expected output, given the input [1,2] would look like

ItemID Difference 
  1      2
  2      0

2 Answers 2

2

Just use conditional aggregatoin:

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

You can include where itemid in (1, 2) (or something similar) if you want to limit this to particular items.

Sign up to request clarification or add additional context in comments.

Comments

0

You can achieve with below mentioned query using case statement and aggregation:

try this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.