【问题标题】:Add averages to column for each group in PostgreSQL将平均值添加到 PostgreSQL 中每个组的列
【发布时间】:2018-11-30 11:15:37
【问题描述】:

我有一个表,其中包含重复名称列表、分数值和分数类型。如何按名称分组,获取每个分数类型的每个名称的平均分值,并将该平均值添加到我创建的名为 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 

【问题讨论】:

    标签: sql postgresql average


    【解决方案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;
    

    【讨论】:

      【解决方案2】:

      使用窗口函数

      select *, 
      avg(SCORE_VALUE) over(partition by NAME,SCORE_TYPE) as AVG_SCORE from t
      

      【讨论】:

        【解决方案3】:
        select
        name
        ,score_type
        ,score_value
        ,avg(score_value) over(partition by name,score_type) as AVG_SCORE
        from [table name]
        

        【讨论】:

        • 感谢您的帮助。
        猜你喜欢
        • 2021-10-21
        • 2015-01-13
        • 2014-08-31
        • 1970-01-01
        • 2023-03-09
        • 2021-12-03
        • 1970-01-01
        • 1970-01-01
        • 2017-03-05
        相关资源
        最近更新 更多