2016-12-02 196 views
0

我有六列的表格如下
Home_Team | Home_Score | Away_Score | Away_Team | Home_Result | Away_Result選擇查詢的MySQL

我要選擇雙贏的HOME_TEAM記錄的輸出,洛斯&領帶比賽。

但是,我使用了以下查詢,而不是計算每個類別中所有匹配項的計數總數。

select a.Home_Team, 
if(a.Home_Result = 'Win', count(a.Home_Result), 0) as Win, 
if(b.Home_Result = 'Loss', count(b.Home_Result), 0) as Loss 
from nsfa.result_main_bck as a 
join nsfa.result_main_bck as b 
on a.Home_Team = b.Home_Team 
where a.Home_Result = 'Win' and b.Home_Result = 'Loss' 
Group by 1 

出了什麼問題在此代碼

我使用MySQL的方式。

問候

回答

1

你不能使用這樣的事情https://stackoverflow.com/a/13075582/285190不知道爲什麼你的加入表上的自我

所以沿着

select a.Home_Team, 
SUM(case when a.Home_Result = 'Win' then 1 else 0 end) as Win 
SUM(case when a.Home_Result = 'Loss' then 1 else 0 end) as Loss 
from nsfa.result_main_bck as a 
where a.Home_Result = 'Win' or a.Home_Result = 'Loss' 
Group By a.Home_Team 

(未測試)

1
if(a.Home_Result = 'Win', count(a.Home_Result), 0) as Win, 

這是一種錯誤的做法,而喲應該使用CASE表達與聚合函數一起像SUM()

sum(case when a.Home_Result = 'Win' then 1 else 0 end) as Win 
+0

親愛的拉胡爾,感謝您的答覆。不過,我得到的結果與您的建議命令相同。 – KhawarAmeerMalik