Di Postgres 9.4 atau lebih baru, gunakan agregat FILTER
pilihan. Biasanya terbersih dan tercepat:
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;
Detail untuk FILTER
klausa:
- Kolom gabungan dengan filter tambahan (berbeda)
Jika Anda ingin pendek :
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;
Varian sintaks lainnya:
- Untuk performa absolut, apakah SUM lebih cepat atau COUNT?
Kueri tab silang yang tepat
crosstab()
menghasilkan kinerja terbaik dan lebih pendek untuk daftar opsi yang panjang:
SELECT * FROM crosstab(
'SELECT category, question1, count(*) 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);
Penjelasan detail:
- Kueri Tab Silang PostgreSQL