4

If I have a table of data as such

name   |   type   |  count

test   | blue     |  6
test2  | red      |  3
test   | red      |  4

How can I query it such that I get a table:

name  |  num_red  | num_blue

test  | 4         | 6
test2 | 3         | 0

I can of course select count(*) where type=blue etc but I can't think of how to count multiple types within one query like this.

Thanks!

1
  • This is fairly basic SQL, so rather than using John's answer verbatim I strongly recommend you read the PostgreSQL tutorial and user manual so you understand why it works and how. Commented Oct 17, 2012 at 22:22

1 Answer 1

6

You can use CASE in you select clause.

SELECT  name,
        SUM(CASE WHEN type = 'red' THEN "count" ELSE 0 END) numred,
        SUM(CASE WHEN type = 'blue' THEN "count" ELSE 0 END) numblue
FROM tableName
GROUP BY name

SQLFiddle Demo

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

1 Comment

how to do dynamic pivot without crosstab !

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.