2017-02-24 63 views
0

我有一個表,它看起來像enter image description here要查找MYSQL最大(總和)爲特定的ID在2組不同的列

我需要的特定TEAM_ID 的目標總和,例如:
如果TEAM_ID 16分進球6和2分別在另一個新列總和將是8 sum_goal

我無法繼續前進。請幫助。

,我曾試圖查詢是:

選擇(match_id,SUM(目標)從 ( 選擇team1_id ID,team1_goal目標從match_result_updation 聯盟所有 選擇team2_id ID,team2_goal目標從match_result_updation )

as A) 

FROM

(SELECT c.tournament_id,克。*
FROM team_trophiesð INNER JOIN tournament_matchË ON e.tournament_id = d.tournament_id INNER JOIN tournament_schedulingÇ ON c.tournament_id = e.tournament_id INNER JOIN 匹配˚F 上 f.match_id = c.id INNER JOIN match_result_updation克 ON g.match_id = f.id WHERE f.match_type = '比賽' 和 d.tournament_id = 1)as p Group by match_id

從第二次select到id = 1我得到的輸出如附件圖片中所示,但我無法找到每個team_id的總和。 如果teamid 16或17 team1或team2相應的目標總和將被計算。

回答

1

我首先想到的是把他們像列,然後總和。 編輯任何SQL引擎

Select ID, Sum(Goal) From 
    (
    Select Team1_ID ID, Team1_Goal Goal From Table 
    Union All 
    Select Team2_ID ID, Team2_Goal Goal From Table 
    ) A 
Group By ID 

PS如果表的設計進行標準化,這種解決辦法的就沒有必要。

+0

我們使用的是MYSQL。 – Rains

+0

我曾嘗試在我的初始代碼中使用給定的上述答案來獲得特定teamid的目標總和,但沒有得到正確的結果集。 – Rains

0

使用此查詢這將有助於總結的目標

select team1_id, sum(team1_goal) as sum_goal from `table` group by `team1_id`; 
+0

這是真的如果id 16位於team2_id上,那麼如何找到總和目標計數? – Rains

0

我們可以這樣做也....

select team1_id, sum(team1_goal) as sum_goal from `table` group by `team1_id` 
union all 
select team2_id, sum(team2_goal) as sum_goal from `table` group by `team1_id`; 

如果你想再次總結可以使用這樣

select t.team_id, sum(t.sum_goal) as total_goal from (
    select team1_id as team_id, sum(team1_goal) as sum_goal from `table` group by `team1_id` 
    union all 
    select team2_id as team_id, sum(team2_goal) as sum_goal from `table` group by `team1_id` 
) as t group by t.team_id; 
0

試試這個

Select ID, Sum(Goal) From 
(
Select Team1_ID ID, Team1_Goal Goal From Table 
Union All 
Select Team2_ID ID, Team2_Goal Goal From Table 
)l, 
table_name Group By ID 
0

另一個版本:

SELECT SUM(nr) 
FROM (
    (SELECT sum(team1_goal) as nr FROM goals WHERE team1_id = 16) 
    UNION ALL 
    (SELECT sum(team2_goal) as nr FROM goals WHERE team2_id = 16) 
) 
sum 
0
 
SELECT team1_id AS Team_ID , sum(team1_goal) as Team_Goal  
FROM 
teams GROUP BY team1_id 
UNION 
SELECT team2_id AS Team_ID , sum(team2_goal) as Team_Goal 
FROM teams GROUP BY team2_id 

這將創建一個表,其中包含每個團隊的ID和每個團隊制定的總目標ID

相關問題