我有一个包含六列的表格如下
Home_Team | Home_Score | Away_Score | Away_Team | Home_Result | Away_Result
我想选择win,loos&的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。
此致
答案 0 :(得分: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
答案 1 :(得分: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
(未经测试)