MYSQL;仅当某个列具有值时才执行SUM

时间:2011-09-09 08:16:33

标签: mysql sum

我有以下代码

$query = "SELECT playerID, name,
  SUM(runs_bowled) / SUM(wickets) AS average
  FROM matchPlayer
  GROUP BY playerID "; 

但是如果这个人没有走过检票口,那么这会返回0,我想要的是

SUM(runs_bowled) / SUM(wickets) AS average

仅在SUM(wickets)大于(或等于)10时才激活。

2 个答案:

答案 0 :(得分:2)

根据您的需要:

SELECT 
    playerID, name,
    IF( SUM(wickets) >= 10, SUM(runs_bowled) / SUM(wickets), NULL ) AS average
FROM matchPlayer
GROUP BY playerID

或者:

SELECT 
    playerID, name,
    SUM(runs_bowled) / SUM(wickets) AS average
FROM matchPlayer
GROUP BY playerID
HAVING SUM(wickets) >= 10

答案 1 :(得分:1)

SELECT playerID, name,
 CASE WHEN wickets >= 10 
      THEN runs / wickets
      ELSE 0
 END As Average
FROM (

SELECT
 playerID, name, 
 SUM(runs_bowled) runs, 
 SUM(wickets) wichets
FROM 
 matchPlayer
GROUP BY 
 playerID, name, 
) As A