agregat FILTER
klausa di Postgres 9.4 atau yang lebih baru lebih pendek dan lebih cepat:
SELECT u.name
, count(*) FILTER (WHERE g.winner_id > 0) AS played
, count(*) FILTER (WHERE g.winner_id = u.id) AS won
, count(*) FILTER (WHERE g.winner_id <> u.id) AS lost
FROM games g
JOIN users u ON u.id IN (g.player_1_id, g.player_2_id)
GROUP BY u.name;
- Panduan
- Wiki Pascagres
- Pos blog Depesz
Di Postgres 9.3 (atau apa saja versi) ini masih lebih pendek dan lebih cepat daripada sub-pilihan bersarang atau CASE
ekspresi:
SELECT u.name
, count(g.winner_id > 0 OR NULL) AS played
, count(g.winner_id = u.id OR NULL) AS won
, count(g.winner_id <> u.id OR NULL) AS lost
FROM games g
JOIN users u ON u.id IN (g.player_1_id, g.player_2_id)
GROUP BY u.name;
Detail:
- Untuk performa absolut, apakah SUM lebih cepat atau COUNT?