有一个历史表,比如
id user vendor createdtime
1 sree a 12/29/2014 23:12:21
1 sree a 12/29/2014 23:13:21
1 sree b 12/29/2014 23:14:21
1 jack a 12/29/2014 23:14:21
1 jack a 12/29/2014 23:11:21
1 sree a 12/29/2014 23:11:21
并需要像
这样的结果id user old vendor new vendor createdtime
1 sree a 12/29/2014 23:12:21
1 sree a a 12/29/2014 23:13:21
1 sree a b 12/29/2014 23:14:21
1 jack b a 12/29/2014 23:14:21
1 jack a a 12/29/2014 23:11:21
1 sree a a 12/29/2014 23:11:21
答案 0 :(得分:1)
select h.id as id , h.[user] as [user],
(select top 1 h2.vendor
from History h2
where h2.[user] = h.[user] and h2.createdtime < h.createdtime
order by h2.createdtime desc ) as [old vendor],
h.vendor as [new vendor]
from History h
order by h.createdtime
答案 1 :(得分:0)
在SQL Server 2012+中,您可以使用lag()
功能:
select h.*, lag(vendor) over (partition by user order by createdtime) as prev_vendor
from history h;
在早期版本中,您可以使用子查询执行此操作。但是,outer apply
更强大:
select h.*, hprev.vendor as prev_vendor
from history h outer apply
(select top 1 h2.*
from history h2
where h2.vendor = h.vendor
order by createdtime
) hprev;
这允许您从上一条记录中提取更多列 - 例如,不仅是供应商名称,还包括createdtime
。