加入多个选择查询SQL

时间:2016-12-21 05:33:17

标签: 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

由于

2 个答案:

答案 0 :(得分:2)

尝试:

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;

答案 1 :(得分:0)

检查这个。

            select id , player_name ,Total_Matches , wintotal

            (
            select players.id,player_name,count(matches.winner) as wintotal from matches,players where matches.winner=players.id 
            group by players.id
            ) A,

            (
            select players.id,player_name,count(*) as Total_Matches from matches,players where matches.winner=players.id or 
            matches.loser=players.id 
            group by players.id
            ) B

            where A.id=B.ID