2012-07-20 114 views
0

您可能需要一些板球知識來幫助解決這個問題。鑑於下表,這個查詢會產生這個結果嗎?擊球平均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 
+0

* * - 你試試吧 「將這個查詢產生這樣的結果?」? (它看起來似乎有道理,但'AS'似乎在錯誤的地方) – Flexo 2012-07-20 15:05:30

回答

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

+0

謝謝。 b1和b2是指什麼? – 24ma13wg 2012-07-20 15:27:14

+0

他們是擊球手錶的別名。我正在使用b1/b2來引用數據來自哪裏 – Taryn 2012-07-20 15:28:03

+0

我會給它一個。謝謝。 – 24ma13wg 2012-07-20 15:36:43