簡體   English   中英

SQL中如何將兩個不同查詢的結果組合成一個查詢

[英]How to combine the results of two different queries into a single query in SQL

我有一個查詢,顯示數據庫中各個球隊贏得的比賽總數,

select t.name, count(*) 'Matches_Won' 
from test.team t 
inner join test.match_scores m on m.winner = t.id 
group by t.name 
order by Matches_Won desc; 

另一個查詢打印出數據庫中各個球隊的比賽總數,

select t.name, count(*) 'Matches_PLayed' from test.team t inner join test.results r on r.home_team = t.id or r.away_team = t.id group by t.name
order by Matches_Played desc; 

現在,我正在嘗試組合這兩個查詢,我想要一個包含三列的表,

  1. 隊名
  2. 打過的比賽
  3. 比賽獲勝

我試圖聯合這兩個查詢,但沒有奏效。 任何人都可以指導我嗎?

這是團隊表

在此處輸入圖像描述

這是比賽得分表 在該表中,“主隊”、“客隊”列代表各隊的進球數,“贏家”是外鍵,指的是球隊表。

在此處輸入圖像描述

這是Results Table ,其中home_teamaway_teamforeign keys referring to the Teams Table

在此處輸入圖像描述

你可以根據 team_name 而不是 union 加入他們嗎?

select 
matchesplayed.name ,Matches_Won,Matches_PLayed
from 
(
select t.name, count(*) 'Matches_PLayed' from test.team t inner join test.results r on r.home_team = t.id or r.away_team = t.id group by t.name
) matchesplayed
LEFT JOIN (select t.name, count(*) 'Matches_Won' 
from test.team t 
inner join test.match_scores m on m.winner = t.id 
group by t.name  ) matchesown
ON matchesown.name = matchesplayed.name
order by 1

現在,如果一支球隊輸掉了所有比賽,他們也會在比賽獲勝列中顯示 null(使用左連接)。

聯合聯合兩個結果集。 你想要兩個結果,比如合並。

以下陳述未被證明,但它應該向您展示解決方案的想法。 您必須在一個查詢中同時加入結果和玩過的游戲。

select t.name, count(distinct m.id) 'Matches_Won', count(distinct r.id) 'Matches_PLayed' 
from test.team t 
left join test.match_scores m on m.winner = t.id 
left join test.results r on r.home_team = t.id or r.away_team = t.id
group by t.name 
order by Matches_Won, Matches_Played desc; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM