我有几张桌子:
users - id
users_matches - user_id, match_id, team
matches - id, winner
我想知道用户有多少胜利,损失和关系。 team
是一个整数,可以是1或2. winner
也是一个整数,但它可以是1(团队1胜),2(团队2胜)或3(领带)。< / p>
我不确定如何在Postgres中将分组count
与嵌套查询混合。
答案 0 :(得分:2)
假设参照完整性和Postgres 9.4:
SELECT *, total - wins - ties AS losses
FROM (
SELECT count(*) AS total
, count(*) FILTER (WHERE m.winner = um.team) AS wins
, count(*) FILTER (WHERE m.winner = 3) AS ties
FROM users_matches um
JOIN matches m ON m.id = um.match_id
WHERE um.user_id = 123; -- for one given user
) sub;
关于聚合FILTER
子句(Postgres 9.4引入):