Det samlede FILTER
klausul i Postgres 9.4 eller nyere er kortere og hurtigere:
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;
- Manualen
- Postgres Wiki
- Depesz blogindlæg
I Postgres 9.3 (eller enhver version) dette er stadig kortere og hurtigere end indlejrede undervalg eller CASE
udtryk:
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;
Detaljer:
- Er SUM hurtigere eller COUNT for absolut ydeevne?