我有一个表,其中包含重复名称,得分值和得分类型的列表。如何按名称分组,获取每种分数类型的每个名称的分数值的平均值,然后将此平均值添加到我创建的称为avg_score的浮点列中?示例:
NAME SCORE_TYPE SCORE_VALUE AVG_SCORE << Desired Output
bob base_score 5 4
bob base_score 4 4
bob base_score 3 4
bob revised_score 1 3
bob revised_score 5 3
bob revised_score 3 3
jack base_score 5 5
jack base_score 7 5
jack base_score 3 5
jack revised_score 1 1
jack revised_score 1 1
jack revised_score 1 1
答案 0 :(得分:1)
使用窗口功能
select *,
avg(SCORE_VALUE) over(partition by NAME,SCORE_TYPE) as AVG_SCORE from t
答案 1 :(得分:1)
select
name
,score_type
,score_value
,avg(score_value) over(partition by name,score_type) as AVG_SCORE
from [table name]
答案 2 :(得分:1)
如果要将其添加到表中,则需要update
:
update t
set AVG_SCORE = tt.avg_score
from (select name, score_type, avg(score) as avg_score
from t
group by name, score_type
) tt
where tt.name = t.name and tt.score_type = t.score_type;