来自别名的SQL累积总和

时间:2015-12-22 08:26:46

标签: postgresql alias cumulative-sum

我想根据我在同一查询中生成的百分比来计算累积总和。我知道累积的方法:

select sum(grandtotal)over(order by agentname) as cumulative from data

但是现在我想要累积的专栏还没有在数据库中。它是在同一个查询中生成的(别名:百分比)

 SELECT 
 agentname,weakness,
 count(*) as frequency,
 count(*)*100.00/sum(count(*))over(order by agentname) as percentage
 from ... where ...

我试试:

(select sum(percentage)over(order by agentname) as cumulative from data

出现错误,说“百分比”列不存在。我如何申请累积金额?谢谢

这个表看起来像我想要的输出:

    agentname | weakness | frequency | percentage | cumulative
       A      |   W1     |     4     |    36.36   |    36.36
       A      |   W2     |     4     |    36.36   |    72.72
       A      |   W3     |     2     |    18.18   |    90.09
       A      |   W4     |     1     |     9.09   |     100

1 个答案:

答案 0 :(得分:1)

无法根据同一SELECT(在大多数数据库中)的另一个窗口函数的结果计算窗口函数。

您必须再次嵌套该查询:

SELECT t.*, SUM(percentage) OVER (ORDER BY agentname) AS cumulative
FROM (
  SELECT 
    agentname,
    weakness,
    COUNT(*) AS frequency,

    -- No ORDER BY in this SUM()!
    COUNT(*) * 100.00 / SUM(COUNT(*)) OVER () AS percentage
  FROM ... WHERE ...
) AS t
ORDER BY agentname

进一步的反馈:

在您了解情况时,我建议您通过向其中添加其他列来确定ORDER BY条款的确定性,例如: weakness

此外,我不确定您的要求,但我认为这些百分比需要按agentname计算?在这种情况下,您必须在PARTITION BY agentname窗口函数中添加SUM(COUNT(*)) OVER(...)子句。