计算查询中的分钟数

时间:2012-04-07 19:48:51

标签: mysql sql count sum

我正在寻找一种方法来计算我队中每个球员(或者这里只有一个球员)的上场时间。简化的数据库表如下:

matchid    action    minute    player
-------------------------------------
1          subbedin  30        Pele 
2          starter             Pele
2          subbedout 50        Pele
3          subbedin  70        Pele
3          red       80        Pele
4          starter             Pele

我现在对其他统计数据的查询:

$query = mysql_query("SELECT *,
  SUM(CASE WHEN action = 'starter' OR action = 'subbedin' THEN 1 ELSE 0 END) AS games,
  SUM(CASE WHEN action = 'goal' OR action = 'pengoal' THEN 1 ELSE 0 END) AS goals,
  SUM(CASE WHEN action = 'yellow' THEN 1 ELSE 0 END) AS yellows,
  SUM(CASE WHEN action = 'red' THEN 1 ELSE 0 END) AS reds,
  // MINS GOES HERE
FROM league2012
GROUP BY player");

对于每个matchid,基本计算是

( 90 OR subbedout OR red ) - ( starter OR subbedin )

例如在比赛2中

subbedout (50) - starter (0) = 50

最后,表格应该像这样:

player    minutes    goals, cards, etc.
---------------------------------------
Pele      210        ...

过去一小时我一直在阅读教程,似乎无法弄清楚如何去做。

2 个答案:

答案 0 :(得分:3)

  sum
    (
      case action
        when 'subbedin'  then 90 - minute
        when 'starter'   then 90
        when 'subbedout' then minute - 90
        when 'red'       then minute - 90
      end
    ) as minutes

答案 1 :(得分:1)

我会首先计算每场比赛每场比赛的上场时间,将其加起来以获得每位球员的总数。为了将获得的结果与您正在计算的其他统计数据相结合,除了以相同的方式执行其他统计数据之外,我看不出其他任何方式,即首先是每个玩家&匹配,然后每个玩家。这就是我的意思:

SELECT
  player,
  SUM(games) AS games,
  SUM(goals) AS goals,
  SUM(yellows) AS yellows,
  SUM(reds) AS reds,
  SUM(minutesplayed) AS minutesplayed
FROM (
  SELECT
    player,
    matchid,
    SUM(CASE WHEN action IN ('starter', 'subbedin') THEN 1 ELSE 0 END) AS games,
    SUM(CASE WHEN action IN ('goal', 'pengoal') THEN 1 ELSE 0 END) AS goals,
    SUM(CASE WHEN action = 'yellow' THEN 1 ELSE 0 END) AS yellows,
    SUM(CASE WHEN action = 'red' THEN 1 ELSE 0 END) AS reds,
    IFNULL(SUM(CASE WHEN action IN ('subbedout', 'red') THEN minute END), 90)
    - IFNULL(SUM(CASE WHEN action = ('subbedin') THEN minute END), 0) AS minutesplayed
  FROM league2012
  GROUP BY
    player,
    matchid
) s
GROUP BY
  player