我有这张桌子
User | days
A | 1
A | 1
A | 2
B | 2
B | 5
我想拥有
User | difference_in_day
A | 0
A | 1
B | 3
我想我必须进行自加入,但我不知道如何将一行与下一行进行比较。
我们是否需要在第一个表中添加一个具有这种条件的行位置?:
WHERE a.row_position+1=b.row_position
请试试:
;with T as(
select *, ROW_NUMBER() over (order by User, Days) Rnum from YourTable
)
select
distinct a.User,
b.Days-a.Days difference_in_day
from T a left join T b on a.Rnum=b.Rnum-1
where b.User is not null
样本
declare @tbl as table(xUser nvarchar(1), xDays int)
insert into @tbl values
('A', 1),
('A', 1),
('A', 2),
('B', 2),
('B', 5)
select *, ROW_NUMBER() over (order by xUser, xDays) Rnum from @tbl
;with T as(
select *, ROW_NUMBER() over (order by xUser, xDays) Rnum from @tbl
)
select
distinct a.xUser,
b.xDays-a.xDays difference_in_day
from T a left join T b on a.Rnum=b.Rnum-1
where b.xUser is not null