0

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;
1
  • 3
    "not working properly"? Um. Edited to provide meaningful title. Commented Dec 23, 2013 at 9:11

1 Answer 1

2

You should not group by noofquestions:

SELECT   id, category, SUM(NULLIF(noofquestions, '')::int), company 
FROM     tableName 
WHERE    id = 1 
GROUP BY id, category, company;
Sign up to request clarification or add additional context in comments.

3 Comments

this is working, but explain the behavior a little if you may.
Aggregate functions like SUM, AVG, MIN and MAX on a table column require the table column in question to be excluded from the GROUP BY clause in order to achieve the desired results.
If you use GROUP BY, then you return one row for each combination of the things in your GROUP BY statement. Any aggregations (like SUM) you put into the select are then used to turn many rows from your original table into a single row in your result. So, if you want to sum together rows with different values of noofquestions, it can't be in your GROUP BY statement.

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.