Running Balance in SQL Server 2012 -
i trying running balance using sql server 2012
here got far...
declare @transactions table ( amount decimal (18,2), transactionid uniqueidentifier, accountid uniqueidentifier, transactiondate date ) declare @accountid uniqueidentifier = newid() insert @transactions (amount, transactionid, accountid, transactiondate) select 3224.99, newid(), @accountid, '2013-06-02' insert @transactions (amount, transactionid, accountid, transactiondate) select 18.99, newid(), newid(), '2013-06-14' insert @transactions (amount, transactionid, accountid, transactiondate) select -8.99, newid(), @accountid, '2013-06-14' insert @transactions (amount, transactionid, accountid, transactiondate) select -6.99, newid(), @accountid, '2013-06-14' insert @transactions (amount, transactionid, accountid, transactiondate) select -22.14, newid(), @accountid, '2014-11-09' insert @transactions (amount, transactionid, accountid, transactiondate) select -84.99, newid(), @accountid, '2013-06-09' select sum(amount) on (order transactiondate, transactionid) [runningbalance], amount @transactions accountid = @accountid order transactiondate desc
results are
runningbalance amount --------------------------------------- --------------------------------------- 3101.88 -22.14 3133.01 -6.99 3124.02 -8.99 3140.00 -84.99 3224.99 3224.99
my goal have runningbalance show each balance, if same day, each row should have own balance
as can see, 2nd row not coming correctly , believe because have 2nd account id conflicting it, assumed statement remove it..
i can remove order by, wanting list newest transaction first, final query have paging, , have tried this.. balance off...
select * ( select sum(amount) on (partition accountid order transactiondate, transactionid) [runningbalance], amount, transactiondate @transactions accountid = @accountid ) results order 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
i'm not sure problem is...
instead of ordering transactionid (a meaningless guid value has no bearing on when row inserted), need determine proper order in other way. since have createdon column stores date/time row inserted, should add order generate correct sequence.
Comments
Post a Comment