在这种情况下,我是否使用命令“ sum”?

时间:2019-05-14 04:41:20

标签: mysql

我想从表格中选择一个足球比赛的结果,将主队得分与客队得分进行比较,并进行总计,如下所示:

  • 如果主队得分为>客队得分= Win
  • 如果<客队得分小于Loss
  • 如果等于=客队得分= Draw

我有2列要使用:hometeamscoreawayteamscore

我知道此代码仅占一列:

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`

3 个答案:

答案 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;