如何比较同一 SQL 服务器 table 中的记录

How to compare records in same SQL Server table

我的要求是将行的每一列与其前一行进行比较。

  1. 比较第 2 行和第 1 行
  2. 比较第 3 行和第 2 行

此外,如果没有区别,我需要将该列设为 NULL。例如:第 3 行的 request_status_id 与第 2 行的相同,因此我需要将第 3 行的 request_status_id 更新为 NULL。

有干净的方法吗?

您可以使用以下 UPDATE 语句,该语句使用 LAG window 从 SQL Server 2012 起可用的函数:

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

SQL Fiddle Demo here

编辑:

OP 的要求似乎是 SET table 的每个 列 到 NULL,以防前一个值与当前值相同。在这种情况下,查询变得有点冗长。这是一个设置了两列的示例。它可以轻松扩展以包含 table:

的任何其他列
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

SQL Fiddle Demo here