SQL Query计算金额变化

时间:2015-09-06 09:15:48

标签: sql-server

任何人都可以帮我了解如何计算某些历史表值的最后一次帐户余额信息变化。

它有如下记录:

accountid     balanceAmount      InsertDate
----------------------------------------------
7282991         200             9/6/2015 0:00
7282991         200             9/5/2015 0:00
7282991         100             9/4/2015 0:00
7282991         100             9/3/2015 0:00
7282991         100             9/2/2015 0:00
929999911       500             9/6/2015 0:00
929999911       500             9/5/2015 0:00
929999911       400             9/4/2015 0:00
929999911       200             9/3/2015 0:00

我需要输出

accountid         lastChange
-----------------------------
7282991              100
929999911            100

1 个答案:

答案 0 :(得分:0)

准备数据

create table #records(accountid varchar(100),balanceamount int,insertdate datetime)

insert into #records values
('7282991',200,'9/6/2015'),
('7282991',200,'9/5/2015'),
('7282991',100,'9/4/2015'),
('7282991',100,'9/3/2015'),
('7282991',100,'9/2/2015'),
('929999911',500,'9/6/2015'),
('929999911',500,'9/5/2015'),
('929999911',400,'9/4/2015'),
('929999911',200,'9/3/2015')

查询

with cte1 as
(
SELECT accountid,balanceamount,insertdate,
balanceamount-LEAD(balanceamount) OVER (partition by accountid ORDER BY insertdate desc) as change
FROM #records
),
cte2 as
(
  select ROW_NUMBER() over(partition by accountid ORDER BY insertdate desc) as rn, * from cte1 where change<>0
)

select accountid,change from cte2 where rn=1