postgresql - 来自别名的 SQL 累积和

标签 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

最佳答案

无法根据同一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 子句具有确定性,例如弱点

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

关于postgresql - 来自别名的 SQL 累积和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34411411/

相关文章:

unix - 在 zsh 中取消全局别名的别名

c - 指针分配受限

mysql 运行总计作为 View

sum - 在 dc.js 中创建运行总和图

mysql - 在 MySQL 中创建累积和列

postgresql - 将包含许多列的 CSV 导入到 pgAdmin v4.1

java - org.postgresql.util.PSQLException : ERROR: maximum number of prepared transactions reached

macos - 带有 iterm 2 的 zsh 无法识别我的别名

mysql - 将 Microsoft SQL Server 数据库复制到 Linux 上的 MySQL/PostgreSQL 的选项

sql - PostgreSQL - 如何创建带条件的窗口框架?