Het geaggregeerde FILTER
clausule in Postgres 9,4 of nieuwer is korter en sneller:
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;
- De handleiding
- Postgres Wiki
- Depesz-blogbericht
In Postgres 9.3 (of elke versie) is dit nog steeds korter en sneller dan geneste subselecties of CASE
uitdrukkingen:
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;
Details:
- Voor absolute prestaties, is SUM sneller of COUNT?