Le agrégat FILTER
clause dans Postgres 9.4 ou plus récent est plus court et plus rapide :
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;
- Le manuel
- Wiki Postgres
- Article de blog Depesz
Dans Postgres 9.3 (ou tout version) c'est encore plus court et plus rapide que les sous-sélections imbriquées ou CASE
expression :
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;
Détails :
- Pour des performances absolues, SUM est-il plus rapide ou COUNT ?