我如何使用 SUM() OVER() [英] How can I use SUM() OVER()
本文介绍了我如何使用 SUM() OVER()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法理解这段代码的错误
I can't understand this code's bug
ID AccountID Quantity
1 1 10 Sum = 10
2 1 5 = 10 + 5 = 15
3 1 2 = 10 + 5 + 2 = 17
4 2 7 = 7
5 2 3 = 7 + 3 = 10
SELECT ID, AccountID, Quantity,
SUM(Quantity) OVER (PARTITION BY AccountID ) AS TopBorcT,
FROM tCariH
推荐答案
似乎您希望查询返回运行总数,但它必须为 AccountID
的两个分区提供相同的值.
Seems like you expected the query to return running totals, but it must have given you the same values for both partitions of AccountID
.
要使用SUM() OVER()
获得运行总数,您需要在PARTITION BY ...
之后添加一个ORDER BY
子句,像这样:
To obtain running totals with SUM() OVER ()
, you need to add an ORDER BY
sub-clause after PARTITION BY …
, like this:
SUM(Quantity) OVER (PARTITION BY AccountID ORDER BY ID)
但请记住,并非所有数据库系统都支持窗口聚合函数的 OVER
子句中的 ORDER BY
.(例如,SQL Server 直到最新版本 SQL Server 2012 才支持它.)
But remember, not all database systems support ORDER BY
in the OVER
clause of a window aggregate function. (For instance, SQL Server didn't support it until the latest version, SQL Server 2012.)
这篇关于我如何使用 SUM() OVER()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文