sql - 加入多个选择查询 SQL

标签 sql postgresql

我有两个具有不同 where 子句的查询,我需要连接这两个查询以获得单个结果表。

第一个查询:

SELECT 
    players.id,player_name,count(matches.winner) as wintotal 
FROM 
    matches, players 
WHERE 
    matches.winner = players.id 
GROUP BY 
    players.id;

它返回这些结果:

 id | player_name |      wintotal 
 45 | Vijay       |        2
 43 | Rahul       |        1
 46 | Shinoy      |        1
 48 | Sunil       |        2
 44 | Adarsh      |        4

第二个查询:

SELECT 
    players.id, player_name, count(*) as totalgames 
FROM 
    matches, players 
WHERE 
    matches.winner = players.id or matches.loser = players.id 
GROUP BY 
    players.id;

返回:

 id | player_name |         Total Matches
 45 | Vijay       |          4
 43 | Rahul       |          2
 46 | Shinoy      |          4
 48 | Sunil       |          2
 44 | Adarsh      |          6
 47 | Pranjal     |          2

在这两个查询中,两个查询的 where 子句不同,最后一列也不同。

  • 第一个查询返回玩家的总胜利数
  • 第二个查询返回玩家参加的总比赛数

如何连接两个查询以在单个查询中同时获得列获胜数和总匹配数?

预期输出:

 id | player_name |         Total Matches | wintotal
 45 | Vijay       |          4            |          2
 43 | Rahul       |          2            |          1
 46 | Shinoy      |          4            |          1
 48 | Sunil       |          2            |          2
 44 | Adarsh      |          6            |          4
 47 | Pranjal     |          2            |          0

谢谢

最佳答案

尝试:

select players.id,
       player_name,
       count(case when matches.winner=players.id then 1 end) as wintotal ,
       count(*) as totalgames
from matches
join players 
on matches.winner=players.id or matches.loser=players.id
group by players.id, 
         player_name;

关于sql - 加入多个选择查询 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41255804/

相关文章:

php - 选择小于一周的 PostgreSQL 表行

mysql - Perl将许多插入语句插入mysql数据库

mysql - 将两个数据库合并为一个数据库

sql - 使用临时表替换 WHERE IN 子句

postgresql - 在可为空的引用上选择

sql - PostgreSQL 中的自定义聚合函数

sql - 从表中编写查询的问题

sql - 在oracle sql中连接没有外键关系的表并向结果添加一列?

sql - 寻找最活跃的话题或游戏

sql - hibernate + spring data 中的 native 插入查询