SQL 来自别名的累计总和
SQL cumulative sum from alias
我想根据我在同一个查询中生成的百分比计算总和。我知道做累积的方法:
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
错误提示 'percentage' 列不存在。我如何应用累计金额?谢谢
这是我想要的输出的 table 样子:
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
(在大多数数据库中)中另一个 window 函数的结果计算 window 函数。
您必须再次嵌套该查询:
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
计算?在这种情况下,您必须在 SUM(COUNT(*)) OVER(...)
window 函数中添加一个 PARTITION BY agentname
子句。
我想根据我在同一个查询中生成的百分比计算总和。我知道做累积的方法:
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
错误提示 'percentage' 列不存在。我如何应用累计金额?谢谢
这是我想要的输出的 table 样子:
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
(在大多数数据库中)中另一个 window 函数的结果计算 window 函数。
您必须再次嵌套该查询:
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
计算?在这种情况下,您必须在 SUM(COUNT(*)) OVER(...)
window 函数中添加一个 PARTITION BY agentname
子句。