我想从表格中选择一个足球比赛的结果,将主队得分与客队得分进行比较,并进行总计,如下所示:
>
客队得分= Win
<
客队得分小于Loss
=
客队得分= Draw
我有2列要使用:hometeamscore
和awayteamscore
。
我知道此代码仅占一列:
SELECT sum(hometeamscore) FROM tablename
我该怎么办才能知道PHP中有多少赢家和输家?
例如:
Game1: Home Team 3 - 0 Away Team
Game2: Home Team 2 - 0 Away Team
Game3: Home Team 1 - 1 Away Team
Game4: Home Team 3 - 2 Away Team
结果:
Win = `2`
Loss = `1`
Draw = `1`
答案 0 :(得分:4)
根据您给定的详细信息,您的表格将如下所示。
CREATE TABLE score (
id INT AUTO_INCREMENT,
hometeamscore TINYINT,
awayteamscore TINYINT,
PRIMARY KEY (id)
) ENGINE=INNODB;
INSERT score (hometeamscore,awayteamscore) values
(3,0),(2,0),(1,1),(1,5);
您需要使用3个简单的查询分别获得赢,输和卓的结果,如下所示:
SELECT count(id) as Win FROM score where hometeamscore > awayteamscore;
SELECT count(id) as Loss FROM score where hometeamscore < awayteamscore;
SELECT count(id) as Drow FROM score where hometeamscore = awayteamscore;
答案 1 :(得分:2)
无法通过一个查询获得结果,但是我们可以使用mysql的UNION
来获取它。您可以得到如下结果:-
SELECT CONCAT('Win:- ', count(id)) as result FROM `scores` WHERE `hometeamscore` > `awayteamscore`
UNION
SELECT CONCAT('Draw:- ',count(id)) as result FROM `scores` WHERE `hometeamscore` = `awayteamscore`
UNION
SELECT CONCAT('Loss:- ',count(id)) as result FROM `scores` WHERE `hometeamscore` < `awayteamscore`
答案 2 :(得分:2)
这也将:
SELECT Result,COUNT(*) AS 'Total' FROM
(SELECT
CASE WHEN hometeamscore > awayteamscore THEN 'Win'
WHEN hometeamscore = awayteamscore THEN 'Draw'
WHEN hometeamscore < awayteamscore THEN 'Loss'
END AS Result
FROM score) v
GROUP BY result;