我的要求是将每一行与前一行进行比较。
另外,如果没有区别,我需要将该列设为NULL。例如:第3行的request_status_id与第2行的request_status_id相同,因此我需要将第3行的request_status_id更新为NULL。
有干净的方法吗?
答案 0 :(得分:2)
您可以使用以下UPDATE
语句,该语句使用从SQL Server 2012开始提供的LAG
窗口函数:
UPDATE #mytable
SET request_status_id = NULL
FROM #mytable AS m
INNER JOIN (
SELECT payment_history_id, request_status_id,
LAG(request_status_id) OVER(ORDER BY payment_history_id) AS prevRequest_status_id
FROM #mytable ) t
ON m.payment_history_id = t.payment_history_id
WHERE t.request_status_id = t.prevRequest_status_id
修改强>
OP的要求似乎是SET
表的每个列
如果前一个值与当前值相同,则为NULL
。在这种情况下,查询变得更加冗长。这是一个设置了两列的示例。它可以很容易地扩展到包含表格的任何其他列:
UPDATE #mytable
SET request_status_id = CASE WHEN t.request_status_id = t.prevRequest_status_id THEN NULL
ELSE T.request_status_id
END,
request_entity_id = CASE WHEN t.request_entity_id = t.prevRequest_entity_id THEN NULL
ELSE t.request_entity_id
END
FROM #mytable AS m
INNER JOIN (
SELECT payment_history_id, request_status_id, request_entity_id,
LAG(request_status_id) OVER(ORDER BY payment_history_id) AS prevRequest_status_id,
LAG(request_entity_id) OVER(ORDER BY payment_history_id) AS prevRequest_entity_id
FROM #mytable ) t
ON m.payment_history_id = t.payment_history_id