我在Microsoft SQL Server中有此表:
Id Date Value
111 1/1/19 1
111 2/1/19 2
222 5/1/19 4
222 4/1/19 3
有没有一种方法可以将数据重新排列成这样:
Id OldDate NewDate OldValue NewValue
111 1/1/19 1/2/19 1 2
222 4/1/19 5/1/19 3 4
答案 0 :(得分:1)
使用lag()
:
select t.*
from (select t.*,
lag(date) over (partition by id order by date) as prev_date,
lag(value) over (partition by id order by date) as prev_value
from t
) t
where prev_date is not null;