美文网首页
pgsql count 条件查询

pgsql count 条件查询

作者: cuihaomaster | 来源:发表于2020-01-08 14:21 被阅读0次

Postgres 9.4以上

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;

随意版本,可以简写

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;

相关文章

网友评论

      本文标题:pgsql count 条件查询

      本文链接:https://www.haomeiwen.com/subject/pncsactx.html