Postgres 9.4 introduced a new, cleaner FILTER aggregate:
SELECT category , count(*) FILTER (WHERE question1 = 0) AS zero , count(*) FILTER (WHERE question1 = 1) AS one , count(*) FILTER (WHERE question1 = 2) AS two FROM reviews GROUP BY 1;
Details for the new FILTER offer:
- How can I simplify this query of game statistics?
If you want briefly:
SELECT category , count(question1 = 0 OR NULL) AS zero , count(question1 = 1 OR NULL) AS one , count(question1 = 2 OR NULL) AS two FROM reviews GROUP BY 1;
Overview of options:
Correct crosstab query
crosstab() gives better performance and shorter for longer option lists:
SELECT * FROM crosstab( 'SELECT category, question1, count(*)::int AS ct FROM reviews GROUP BY 1, 2 ORDER BY 1, 2' , 'VALUES (0), (1), (2)' ) AS ct (category text, zero int, one int, two int);
Detailed explanation:
- PostgreSQL crosstab query
Erwin brandstetter
source share