与一些算术集合聚合(合并相似的行)

时间:2015-08-27 20:30:44

标签: sql postgresql group-by aggregate-functions average

我需要合并以下行:

id num_votes avg_vote
1      2      4
1      3      1
1      0      0

最终得到这个:

id num_votes avg_votes
1   2+3+0=5      4*2/5 + 3*1/5 = 2.2

我已尝试过以下操作,当然,聚合嵌套函数无法正常工作:

select id
     , sum(num_votes) as _num_votes
     , sum(num_votes/sum(num_votes)*avg_vote) as _avg_vote
from mytable
GROUP BY id, num_votes, avg_vote;

1 个答案:

答案 0 :(得分:1)

SELECT id
     , sum(num_votes) as _num_votes
     , round(  sum(num_votes * avg_vote)::numeric
             / sum(num_votes)
           , 2) AS avg_votes
FROM   mytable
GROUP  BY id; -- you cannot GROUP BY aggregated columns, just: id

SQL Fiddle.

您不需要窗口功能。聚合函数可以完成这项工作。

计算:

4*2/5 + 3*1/5 + 0*0/5

可以改写为:

(4*2 + 3*1 + 0*0)/5

实施为:

sum(num_votes * avg_vote) / sum(num_votes)

其余的是转换和舍入以保留小数位数。 (整数除法会截断。)