2014-12-29 99 views
0

我有一個團隊統計數據庫,我想規範一個特定統計的總和。例如,我有多餘的記錄,像這樣的表:計算和使用子查詢中的列平均值

team_name | team_code | player | steal | block 
Team A | TA  | PA  | 100 | 100 
Team A | TA  | PA  | 100 | 100 
Team A | TA  | PA  | 100 | 100 
Team B | TB  | PB  | 200 | 200 
Team C | TC  | PC  | 300 | 300 
Team C | TC  | PC  | 300 | 300 

我想獲得球隊(搶斷+塊)對所有的球員,除以均值(偷+塊)的所有球隊。

例如,我需要的輸出看起來像這樣(注:我在我需要norm_def_total表達增加):

team_name | team_code | steal_sum | block_sum | def_total | norm_def_total 
Team A | TA  | 300  | 300  | 600  | 600/(avg(def_total)) 
Team B | TB  | 200  | 200  | 400  | 400/(avg(def_total)) 
Team C | TC  | 600  | 600  | 1200  | 1200/(avg(def_total)) 

這裏是我的嘗試:

 
SELECT b.team_name, b.team_code, b.def_total/AVG(b.def_total) normalized_def FROM 
(
    SELECT team_name, 
     team_code, 
     SUM(steal) steal_sum, 
     SUM(block) block_sum, 
     CAST(SUM(steal) + SUM(block) AS double precision) def_total 
    FROM gamelog 
    WHERE team_name IN (SELECT DISTINCT (team_name) FROM gamelog) 
    GROUP BY team_name, 
      team_code 
    ORDER BY def_total DESC 
) b 
GROUP BY 
    b.team_name, 
    b.team_code, 
    b.def_total 

從以上,我的問題是b.def_total/AVG(b.def_total)總是返回1.我認爲它只是針對該特定團隊採用AVG,但我想要b的所有團隊的AVG。如何從計算中得到b的實際平均值?

回答

3

試試這個。

SELECT b.team_name, 
     b.team_code, 
     Sum(def_total)/Avg(b.def_total)OVER(partition BY NULL) 
FROM (SELECT team_name, 
       team_code, 
       Sum(steal)          steal_sum, 
       Sum(block)          block_sum, 
       Cast(Sum(steal) + Sum(block) AS DOUBLE PRECISION) def_total 
     FROM gamelog 
     WHERE team_name IN (SELECT DISTINCT (team_name) 
          FROM gamelog) 
     GROUP BY team_name, 
        team_code 
     ORDER BY def_total DESC) b 
GROUP BY b.team_name, 
      b.team_code 
+0

這工作,謝謝!我從來沒有使用過,但我會檢查OVER(PARTITION BY NULL)究竟是做什麼的。 –

+0

不錯的解決方案我不熟悉OVER(PARTITION BY NULL)。我研究了PostGres窗口函數,它們非常酷。如果你想了解一些關於它們的內容,請看看這個:http://www.postgresql.org/docs/9.1/static/tutorial-window.html。 MySQL並不支持這一點,這讓人很失望。 – halmeetdave

0

嘗試類似:

SELECT team_name, 
     team_code, 
     sum(steal) as steal_sum, 
     sum(block) AS block_sum, 
     sum(steal) + sum(block) AS def_total, 
     ((sum(steal) + sum(block))/sum(steal) + sum(block))/count(*) AS norm_def_total 
FROM gamelog 
GROUP BY team_name, team_code