TSQL - 从下一个相邻行填充记录

时间:2012-12-06 15:31:03

标签: sql-server tsql sql-server-2008-r2

当前输出

Activity            FromTime                ToTime
-------------------------------------------------------------------
STOPPED INSIDE POI  2012-11-14 01:08:46.000 2012-11-14 01:19:46.000
MOVING INSIDE POI   2012-11-14 01:20:46.000 2012-11-14 01:21:46.000
MOVING OUTSIDE POI  2012-11-14 01:22:46.000 2012-11-14 01:22:46.000
STOPPED OUTSIDE POI 2012-11-14 01:23:46.000 2012-11-14 01:23:46.000
MOVING OUTSIDE POI  2012-11-14 01:24:46.000 2012-11-14 01:25:46.000

预期产出

Activity            FromTime                ToTime
-------------------------------------------------------------------
STOPPED INSIDE POI  2012-11-14 01:08:46.000 2012-11-14 01:20:46.000
MOVING INSIDE POI   2012-11-14 01:20:46.000 2012-11-14 01:22:46.000
MOVING OUTSIDE POI  2012-11-14 01:22:46.000 2012-11-14 01:23:46.000
STOPPED OUTSIDE POI 2012-11-14 01:23:46.000 2012-11-14 01:24:46.000
MOVING OUTSIDE POI  2012-11-14 01:24:46.000 2012-11-14 01:25:46.000

这样做的简单方法是什么?

2 个答案:

答案 0 :(得分:1)

这应该适合你:

UPDATE table1
SET ToTime = join_table.newToTime
FROM (
  SELECT t2.FromTime target, MIN(t1.FromTime) newToTime 
  FROM table1 t1 
  JOIN table1 t2 ON t1.FromTime > t2.FromTime
  GROUP BY t2.FromTime) join_table
WHERE FromTime = join_table.target

基本上,您正在寻找大于当前行的最小FromTime - 并将其用作ToTime的新值。请注意,最后一行不会更新,因为找不到匹配的大FromTime

答案 1 :(得分:1)

;with a as
(
select Activity, FromTime, ToTime, 
row_number() over (order by FromTime) rn from <yourtable>
)
select a.Activity, a.FromTime, coalesce(b.FromTime, a.ToTime) ToTime
from a left join a b on a.rn = b.rn - 1
order by a.rn