2011-08-08 94 views
0

我有一個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,平均

聽起來很簡單,但對我來說唯一的問題是。 在板球,平均是不SUM(運行)/ COUNT(*) 它的總和(運行)/局的數字的計數,其中how_out不是「不出來」

能有一個人告訴我如何寫一個這樣的查詢?

我寫的查詢出於明顯原因給出了錯誤的平均值。 我寫的查詢是

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

請問sql專家請幫幫我嗎?

感謝

回答

2
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 
+0

不錯 - 你可以,如果剝離IF(),'how_out <>「沒有out''會評估1或0. – wonk0

+0

是的,我知道。我以擴展的形式寫了它,使它更容易被忽略。 :) –

+0

是的,這很有道理 – wonk0

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 
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