Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/sharepoint/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Postgres嵌套SQL查询到计数字段_Sql_Postgresql_Aggregate Functions - Fatal编程技术网

Postgres嵌套SQL查询到计数字段

Postgres嵌套SQL查询到计数字段,sql,postgresql,aggregate-functions,Sql,Postgresql,Aggregate Functions,我有几张桌子: users - id users_matches - user_id, match_id, team matches - id, winner 我想数一数一个用户有多少赢、输和平局team是一个整数,可以是1或2winner也是一个整数,但它可以是1(第1队获胜)、2(第2队获胜)或3(平局) 我不知道如何将分组的计数与Postgres中的嵌套查询混合使用。假设引用完整性和Postgres 9.4: SELECT *, total - wins - ties AS loss

我有几张桌子:

users - id

users_matches - user_id, match_id, team

matches - id, winner
我想数一数一个用户有多少赢、输和平局
team
是一个整数,可以是1或2
winner
也是一个整数,但它可以是1(第1队获胜)、2(第2队获胜)或3(平局)


我不知道如何将分组的
计数与Postgres中的嵌套查询混合使用。

假设引用完整性和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;
关于聚合
过滤器
条款(在Postgres 9.4中介绍):


Postgres 9.4我想是吧?