击球平均MySQL查询

时间:2012-07-20 15:02:49

标签: mysql

你可能需要一些关于板球的知识来帮助解决这个问题。鉴于下表,此查询是否会产生此结果?

Table: batsmen
batsmanname | runsscored | howout
Colin       | 10         | bowled
Colin       | 20         | caught
Steve       | 10         | bowled
Steve       | 20         | not out

SELECT batsmanname, SUM(runsscored) / COUNT(howout) AS battingavg
FROM batsmen 
WHERE howout <> 'not out' 
GROUP BY batsmananme

Result:
batsmanname | battingavg
Colin       | 15
Steve       | 30

1 个答案:

答案 0 :(得分:1)

这应该产生你想要的结果:

SELECT b1.name, SUM(b1.runsscored) / b2.NumOut as bat_avg
FROM batsmen b1
INNER JOIN
(
  select name, COUNT(howout) as NumOut
  from batsmen
  WHERE howout <> 'not out' 
  GROUP BY name
) b2
  ON b1.name = b2.name
GROUP BY b1.name

请参阅SQL Fiddle with demo