我正在尝试使用 SQL Server 2012 获得运行平衡
这是我到目前为止所得到的......
DECLARE @Transactions TABLE
(
Amount decimal (18,2),
TransactionId uniqueidentifier,
AccountId uniqueidentifier,
TransactionDate date
)
DECLARE @AccountId uniqueidentifier = NEWID()
INSERT INTO @Transactions (Amount, TransactionId, AccountId, TransactionDate)
SELECT 3224.99, NEWID(), @AccountId, '2013-06-02'
INSERT INTO @Transactions (Amount, TransactionId, AccountId, TransactionDate)
SELECT 18.99, NEWID(), NEWID(), '2013-06-14'
INSERT INTO @Transactions (Amount, TransactionId, AccountId, TransactionDate)
SELECT -8.99, NEWID(), @AccountId, '2013-06-14'
INSERT INTO @Transactions (Amount, TransactionId, AccountId, TransactionDate)
SELECT -6.99, NEWID(), @AccountId, '2013-06-14'
INSERT INTO @Transactions (Amount, TransactionId, AccountId, TransactionDate)
SELECT -22.14, NEWID(), @AccountId, '2014-11-09'
INSERT INTO @Transactions (Amount, TransactionId, AccountId, TransactionDate)
SELECT -84.99, NEWID(), @AccountId, '2013-06-09'
SELECT SUM(Amount) OVER (ORDER BY TransactionDate, TransactionId) as [RunningBalance],
Amount
FROM @Transactions
WHERE AccountId = @AccountId
ORDER BY TransactionDate DESC
结果是
RunningBalance Amount
--------------------------------------- ---------------------------------------
3101.88 -22.14
3133.01 -6.99
3124.02 -8.99
3140.00 -84.99
3224.99 3224.99
我的目标是让 RunningBalance 显示每个余额,即使是同一天,每一行也应该有自己的余额
如您所见,第二行没有正确显示,我相信这是因为我还有一个与之冲突的第二个帐户 ID,但假设 WHERE 语句会删除它..
我可以删除 ORDER BY,但是我希望我的列表是最新的交易,因为最终查询将有分页,我已经尝试过这样的事情..但余额已关闭......
SELECT * FROM (
SELECT SUM(Amount) OVER (PARTITION BY AccountId ORDER BY TransactionDate, TransactionId) as [RunningBalance],
Amount, TransactionDate
FROM @Transactions
WHERE AccountId = @AccountId
) AS Results
ORDER BY TransactionDate DESC
RunningBalance Amount TransactionDate
--------------------------------------- --------------------------------------- ---------------
3101.88 -22.14 2014-11-09
3131.01 -8.99 2013-06-14
3124.02 -6.99 2013-06-14
3140.00 -84.99 2013-06-09
3224.99 3224.99 2013-06-02
我不太确定问题是什么...