我有一张桌子,上面有体育比赛,其中包含日期,球队和成绩。我想找到一支球队目前的胜利或失败。
我的桌子看起来像这样:
+------------+----------+---------+---------------+------+------------+
| date_month | date_day | visitor | visitor_score | home | home_score |
+------------+----------+---------+---------------+------+------------+
| May | 1 | MyTeam | 90 | Z | 100 |
+------------+----------+---------+---------------+------+------------+
| April | 26 | X | 100 |MyTeam| 90 |
+------------+----------+---------+---------------+------+------------+
| April | 21 | Y | 90 |MyTeam| 100 |
+------------+----------+---------+---------------+------+------------+
| March | 25 | MyTeam | 90 | W | 100 |
+------------+----------+---------+---------------+------+------------+
我已经完成了按日期排序结果的任务。
SELECT * FROM Schedule WHERE visitor_score>0
ORDER BY CASE
when `date_month` = 'May' then 1
when `date_month` = 'April' then 2
when `date_month` = 'March' then 3
else 4
end asc, date_day desc
问题是,如何找到一支球队?
Myteam
输了最后两场比赛,因此应该是0
获胜和2
输。但是,如果它在下一场比赛中获胜,则显然应该是1
获胜和0
失败。我知道如何提取胜负(如下),但这是我坚持的重点。
WHERE (visitor = 'MyTeam' && visitor_score>home_score) OR (home = 'MyTeam' && home_score>visitor_score)
最佳答案
我不会抱怨您的表结构。
我假设您不能更改表结构。
我已经完成了按日期排序结果的任务。
您的解决方案很难看。考虑使用类似:
SELECT STR_TO_DATE(CONCAT(date_month, date_day, YEAR(CURDATE())),"%M%d%Y") AS date
请注意,我必须使用YEAR(CURDATE()),因为在STR_TO_DATE函数中必须输入年份,并且似乎没有存储游戏的年份。
现在您可以简单地:
ORDER BY date DESC
现在,我将解释我想到的有关W / L / D(赢,输,平局)连胜的第一个解决方案。
声明3个功能:
resolveLastResult(返回W,L,D)
resolveLastGameDate(返回date_month,date_day)
resolveFirstResultDateDifferentFromLastOne(返回第一个游戏的日期,其结果与最后一个游戏的日期不同)
下面是每个函数的主体的模拟对象。
一旦有了这些功能,您就可以简单地执行以下操作:
SELECT COUNT(*), retrieveLastResult
FROM Schedule
WHERE
STR_TO_DATE(CONCAT(date_month, date_day, YEAR(CURDATE())),"%M%d%Y")
BETWEEN DATE_SUB(retrieveFirstResultDateDifferentFromLastOne(retrieveLastResult,retrieveLastGameDate),INTERVAL 1 DAY)
AND retrieveLastGameDate()
resolveLastResult函数
SELECT
IF(`home` = "MyTeam",
CASE
WHEN `home_score` > `visitor_score` THEN "W"
WHEN `home_score` < `visitor_score` THEN "L"
WHEN `home_score` = `visitor_score` THEN "D"
END,
CASE
WHEN `visitor_score` > `home_score` THEN "W"
WHEN `visitor_score` < `home_score` THEN "L"
WHEN `visitor_score` = `home_score` THEN "D"
END
)
FROM schedule
ORDER BY STR_TO_DATE(CONCAT(date_month, date_day, YEAR(CURDATE())),"%M%d%Y") DESC
LIMIT 1
resolveLastGameDate函数
SELECT STR_TO_DATE(CONCAT(date_month, date_day, YEAR(CURDATE())),"%M%d%Y") as date
FROM schedule
ORDER BY date
LIMIT 1
resolveFirstResultDateDifferentFromLastOne函数
SELECT date
FROM schedule
WHERE
IF(`home` = "MyTeam",
CASE
WHEN `home_score` > `visitor_score` THEN "W"
WHEN `home_score` < `visitor_score` THEN "L"
WHEN `home_score` = `visitor_score` THEN "D"
END,
CASE
WHEN `visitor_score` > `home_score` THEN "W"
WHEN `visitor_score` < `home_score` THEN "L"
WHEN `visitor_score` = `home_score` THEN "D"
END
) != lastResult()
ORDER BY STR_TO_DATE(CONCAT(date_month, date_day, YEAR(CURDATE())),"%M%d%Y") DESC
LIMIT 1