在sql中的同一个表中,通过下一行的另一列更新两列

时间:2016-02-04 06:34:21

标签: sql-server

这是我的桌子 enter image description here

我的输出应该是 enter image description here

我想使用下一个closed_date,time更新new_class_desc ='FLM'的{​​{1}},但如果Update_date,Update_timenew_class_desc,则忽略它并将下一个日期更新为{{ 1}}

我尝试的查询有点像这样..

'FollowupComments'

但在此我没有将Closed_date update_date作为;WITH cte as( SELECT * ,row_number() OVER(ORDER BY Update_date,Update_time) rn FROM Table WHERE Problem_sid = 1435819 ) UPDATE c1 SET Closed_date = c2.Update_date, Closed_time = c2.Update_time FROM cte c1 JOIN cte c2 ON c1.rn = c2.rn - 1 AND c1.New_class_desc = 'FLM' AND c2.New_class_desc <> 'FLM' AND c2.New_class_desc not in ('FollowUpComments') 获取给Flm。

请在这里指导。

1 个答案:

答案 0 :(得分:0)

WITH cte
AS
(
    SELECT *, ROW_NUMBER() OVER(ORDER BY t.Update_date, t.Update_time) AS  rno  
    FROM my_Table t 
    WHERE t.New_class_desc <> 'FollowUpComments'
)
UPDATE t
SET t.Closed_Date = t1.Closed_Date,
t.Closed_Time = t1.Closed_Time
FROM cte t 
JOIN cte t1 ON t.rno = t1.rno + 1 
WHERE t.New_class_desc = 'FLM'