我想从我在同一个查询中生成的百分比中进行累积和。我知道累积的方法:
select sum(grandtotal)over(order by agentname) as cumulative from data
但现在我想做的累积的列还不在数据库中。在同一个查询中生成(别名:percentage)
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
最佳答案
不能基于同一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(...)
子句。关于postgresql - 别名的SQL累积总和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34411411/