我无法理解这段代码的错误
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
答案 0 :(得分:27)
似乎您希望查询返回正在运行的总计,但它必须为AccountID
的两个分区提供相同的值。
要获得SUM() OVER ()
的运行总计,您需要在ORDER BY
之后添加PARTITION BY …
子句,如下所示:
SUM(Quantity) OVER (PARTITION BY AccountID ORDER BY ID)
但请记住,并非所有数据库系统都支持窗口聚合函数的ORDER BY
子句中的OVER
。 (例如,SQL Server在最新版本SQL Server 2012之前不支持它。)
答案 1 :(得分:7)
如果您使用的是SQL 2012,则应尝试
SELECT ID,
AccountID,
Quantity,
SUM(Quantity) OVER (PARTITION BY AccountID ORDER BY AccountID rows between unbounded preceding and current row ) AS TopBorcT,
FROM tCariH
如果可用,按日期列更好的排序。
答案 2 :(得分:2)
查询将是这样的:
SELECT ID, AccountID, Quantity,
SUM(Quantity) OVER (PARTITION BY AccountID ) AS TopBorcT
FROM #Empl ORDER BY AccountID
按照分组的方式进行分区。这里我们按AccountID进行分组,因此总和将与AccountID相对应。
第一个案例,AccountID = 1,然后sum(数量)= 10 + 5 + 2 => 17&对于AccountID = 2,则sum(Quantity)= 7 + 3 => 10
因此结果会显示为附加snapshot。