我第一次使用SUM并且有以下查询noe:
SELECT Id, Amount, Date, TotalAmount = SUM(Amount) OVER (order by Amount)
FROM Account
WHERE Date >= '2016-03-01' AND Date <= '2016-03-10' AND UserId = 'xyz'
ORDER BY ValutaDate
对于特定用户,TotalAmount
应该是整个表的运行总计(因此Sum Over子句应该尊重用户的where子句)。另一方面,我只需要一些记录,而不是整个表,这就是为什么我添加了指定日期范围的where子句。但是现在,当然,我的总和仅根据我指定的范围计算。
我该怎么做,只获得一些由日期范围指定的记录,但得到在整个表格中计算的总和。是否有一种高效的方法来实现这一目标?
先谢谢你帮助我。
答案 0 :(得分:1)
首先应用WHERE子句,以便SUM无法访问与之不匹配的行。 你可以使用申请。请注意,它将为该用户读取整个表格,因此如果没有合适的索引,可能效果不佳。
SELECT a.Id, a.Amount, a.Date, ta.TotalAmount
FROM Account a
OUTER APPLY (SELECT SUM(CASE WHEN a2.Date <= Account.Date THEN a2.TotalAmount ELSE 0 END) AS TotalAmount FROM Account a2 WHERE a2.UserId = Account.UserId) ta
WHERE a.Date >= '2016-03-01' AND a.Date <= '2016-03-10' AND a.UserId = 'xyz'
答案 1 :(得分:1)
将运行总计分解为自己的查询
; WITH all_rows_one_user as (SELECT *
, TotalAmount = SUM(Amount) OVER (order by ValutaDate)
FROM Account
WHERE UserId = 'xyz')
SELECT Id, Amount, Date, TotalAmount
FROM all_rows_one_user
WHERE Date >= '2016-03-01' AND Date <= '2016-03-10'
ORDER BY ValutaDate
相同的查询,不同的语法:
SELECT Id, Amount, Date, TotalAmount
FROM (SELECT *
, TotalAmount = SUM(Amount) OVER (order by ValutaDate)
FROM Account
WHERE UserId = 'xyz') AS all_rows_one_user
WHERE Date >= '2016-03-01' AND Date <= '2016-03-10'
ORDER BY ValutaDate