mysql查询计算板球击球手的平均值

时间:2011-08-08 13:38:33

标签: mysql

我有一个mysql表,它包含这样的数据。

Name    |how_out    |runs
------------------------------
Robin   |Not out    |45
Robin   |lbw        |25
Robin   |caught     |50
Robin   |caught     |0
Robin   |bowled     |30
Robin   |bowled     |0
.
.
.

我想要一个SQL查询,它返回以下列

姓名,Total_runs,平均

听起来很简单,但对我来说唯一的问题是。 在板球中,平均值不是总和(运行)/计数(*) 它是总和(运行)/ how_out不是'不出'的局数的计数

有人可以告诉我如何写一个这样的查询吗?

由于显而易见的原因,我写的查询给出了错误的平均值。 我写的查询是

Select `Name`,sum(`runs`) as 'Total_runs', Sum(`runs`)/count(*)
From `batsman_stats`
group by `Name`
order by 2 desc

sql专家可以帮帮我吗?

由于

3 个答案:

答案 0 :(得分:3)

Select `Name`,sum(`runs`) as 'Total_runs', Sum(`runs`)/sum(if(how_out <> 'Not out',1,0))
From `batsman_stats`
group by `Name`
order by 2 desc

答案 1 :(得分:2)

我认为你需要一个子选择:

Select Name, sum(runs) as Total_runs, Sum(runs)/(
   select count(*) from batsman_stats b
   where b.Name=a.Name and not b.how_out = 'Not out'
)
From batsman_stats a
group by Name
order by 2 desc

答案 2 :(得分:1)

You could use a CASE statement

SELECT Name,
       SUM(Runs) as Total_runs, 
       SUM(Runs)/COUNT(CASE WHEN how_out <> 'Not out' THEN 1 END) as Average
FROM batsman_stats
GROUP BY Name
ORDER BY SUM(Runs) DESC