v0ld3m0rt
v0ld3m0rt

Reputation: 904

How to formulate a conditional sum in PostgreSQL?

I have a table containing id, category, noofquestions and company. I want a query which would return the noofquestions as sum of the values of noofquestions when category is same in two or more columns. I'm trying this query but it is only adding those columns whose category is same and noofquestions are equal which is wrong. It should not check for noofquestions.

 SELECT id ,  category,   SUM(NULLIF(noofquestions, '')::int), company 
 FROM tableName   
 WHERE id=1 
 GROUP BY id, category, noofquestions, company;

Upvotes: 0

Views: 757

Answers (1)

Mureinik
Mureinik

Reputation: 311316

You should not group by noofquestions:

SELECT   id, category, SUM(NULLIF(noofquestions, '')::int), company 
FROM     tableName 
WHERE    id = 1 
GROUP BY id, category, company;

Upvotes: 2

Related Questions