两次录音之间的天数差异

时间:2013-05-02 10:38:21

标签: sql self-join

我有这张桌子

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 

1 个答案:

答案 0 :(得分:0)

请尝试:

;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