用例来查找百分比 - SELECT CASE子查询

时间:2015-12-10 18:17:47

标签: mysql subquery case percentage

几乎是MySQL的初学者。现在通过Lynda.com学习。

我有一个包含以下表格的数据库

tblmatches - matchID, matchdate, matchtime, matchstatus, teamhomeID,    teamAwayID, matchscorehome, matchscoreaway, seasonID, competitonID
tblteam - teamID, teamName

我试图找出每支球队有多少场比赛,两队都得分。

我正在使用以下声明,该声明可以找到所玩的游戏数量(p),所有游戏中有多少游戏得分(y),但无法确定如何获得百分比。

我按teamName分组,必须使用主场和客场比赛

SELECT
teamName AS Team, 
Sum(P) AS P,
SUM(Y) AS Y
FROM(
    SELECT
    teamHomeID Team,
    1 P,
    CASE WHEN matchScoreHome AND matchScoreAway > 0 THEN 1 ELSE 0 END Y 
    FROM tblmatches WHERE matchstatus = 'FT' AND competitionID = 1         AND     seasonID = 2
  UNION ALL
  SELECT
   teamAwayID,
   1,
   CASE WHEN matchScoreHome AND matchScoreAway > 0 THEN 1 ELSE 0 END Y
  FROM tblmatches WHERE matchstatus = 'FT' AND competitionID = 1 AND      seasonID = 2
  ) as tab
 JOIN tblteam t ON tab.team=t.teamID
 GROUP BY Team
ORDER BY SUM(Y) DESC ;

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

找到答案,因为仍然学习没有实现mysql的工作,但从引号之间的什么开始。在那一点上,我意识到SUM必须在子查询之外,通过谷歌进行一点搜索并且知道要放入初始SELECT

SELECT
teamName AS Team, 
Sum(P) AS P,
SUM(Y) AS Y,
(SUM(Y) * 100) / SUM(P) AS 'BTTS PCT'
FROM(
    SELECT
    teamHomeID Team,
    1 P,
    CASE
    WHEN matchScoreHome AND matchScoreAway > 0 THEN 1 ELSE 0 
   END Y 
  FROM tblmatches WHERE matchstatus = 'FT' AND competitionID = 1        AND seasonID = 2
   UNION ALL
   SELECT
   teamAwayID,
   1,
   CASE 
    WHEN matchScoreHome AND matchScoreAway > 0 THEN 1 ELSE 0 
    END Y
   FROM tblmatches WHERE matchstatus = 'FT' AND competitionID = 1 AND   seasonID = 2 
   ) as tab
  JOIN tblteam t ON tab.team=t.teamID
 GROUP BY Team
 ORDER BY SUM(Y) DESC ;