2016-12-21 95 views
0

我有兩個不同的where子句的查詢,我需要連接兩個查詢來獲得單個結果表。加入多個select查詢SQL

首先查詢:

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 

感謝

+0

[不良習慣踢:使用舊樣式的JOIN(http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/08/bad-habits-to-kick-using-old -style-joins.aspx) - 在ANSI - ** 92 ** SQL標準中,舊式*逗號分隔的表*樣式列表已替換爲* proper * ANSI'JOIN'語法(**超過20年**之前),其使用是不鼓勵的 –

回答

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; 
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