I am trying to query for an amount when it changes base on a record. For example the below table below.
I want to query for the rows with a (****). I want to know whenever the balance changes for each acct. Once i have that i want to show the difference from the latest balance to the previous balance change… so for acct 123456 i want to query for when balance change from 1000 to 2000 and show the difference in another query does not need to be all in one query. Hope i am making sense any help is appreciated.
ACCT BALANCE TIME
123450 1000.00 2008-01-30 00:00:00.000****
123456 1000.00 2008-02-29 00:00:00.000
123456 1000.00 2008-03-31 00:00:00.000
123456 1000.00 2008-04-30 00:00:00.000
123456 1000.00 2008-05-31 00:00:00.000
123456 2000.00 2008-06-30 00:00:00.000****
654321 1000.00 2008-02-29 00:00:00.000
654321 2000.00 2008-03-31 00:00:00.000****
i have found the below but it does not work for what am looking for.
DECLARE @x TABLE(acct INT, balance money,[time] DATETIME)
INSERT @x VALUES
(123450,’1000.00′,’2008-01-30 00:00:00′),–
(123456,’1000.00′,’2008-02-29 00:00:00′),–
(123456,’1000.00′,’2008-03-31 00:00:00′),–
(123456,’1000.00′,’2008-04-30 00:00:00′),–
(123456,’1000.00′,’2008-05-31 00:00:00′),–
(123456,’2000.00′,’2008-06-30 00:00:00′),–
(654321,’1000.00′,’2008-02-29 00:00:00′),–
(654321,’2000.00′,’2008-03-31 00:00:00′);–
select * from @x
; with temp as
(
SELECT
acct, balance, [time], lag(balance) over (order by [time] ) as lastValue
FROM @x
)
SELECT
acct,[time] , balance
FROM
temp
WHERE acct > lastValue
order by acct, time