我有一个团队统计数据库,我想规范化某个统计数据的总和。例如,我有一个冗余记录表,如下所示:
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,但我希望所有团队的AVG都来自b。如何从计算中使用b获得实际平均值?
答案 0 :(得分: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
答案 1 :(得分: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