我有这张桌子:
id ID Date Cumulative
1 x Jan-10 10
3 x Feb-10 40
7 x Apr-10 60
9 x May-10 100
2 y Jan-10 20
6 y Mar-10 40
8 y Apr-10 60
10 y May-10 100
我需要扭转"累积"在MS SQL Server Query中如下
id ID Date Cumulative Reversed
1 x Jan-10 10 10
3 x Feb-10 40 30
7 x Apr-10 60 20
9 x May-10 100 40
2 y Jan-10 20 20
6 y Mar-10 40 20
8 y Apr-10 60 20
10 y May-10 100 40
注意:查询适用于SQL Server 2012
答案 0 :(得分:7)
您可以使用lag
获取上一行中的值,并从当前行的值中减去以获得反转值。
select t.*, cumulative - coalesce(lag(cumulative) over(partition by id order by date),0) as reversed
from tablename t
来自@Gordon Linoff的评论..您可以使用lag(cumulative,1,0)
代替coalesce
。
select t.*, cumulative-lag(cumulative,1,0) over(partition by id order by date) as reversed
from tablename t
答案 1 :(得分:1)
对于使用递归CTE的以下Sql server 2012
declare @t table(id int,IDs varchar(20),Dates varchar(20),Cumulative int)
insert into @t values
(1,'x','Jan-10', 10)
,(3,'x','Feb-10', 40)
,(7,'x','Apr-10', 60)
,(9,'x','May-10', 100)
,(2,'y','Jan-10', 20)
,(6,'y','Mar-10', 40)
,(8,'y','Apr-10', 60)
,(10,'y','May-10',100)
;With CTE as
(select *,row_number()over(partition by ids order by id)rn
from @t
)
,CTE1 as
(select id,ids,dates, Cumulative,rn,Cumulative Reversed
from cte where rn=1
union all
select c.id,c.ids,c.Dates,c.Cumulative,c.rn
,c.Cumulative-c1.Cumulative
from cte c
inner join cte c1 on c.ids=c1.ids
where c.rn=c1.rn+1
)
select * from cte1