如何比较同一SQL Server表中的记录

时间:2015-02-06 12:58:29

标签: sql-server sql-server-2012

enter image description here

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

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

    有干净的方法吗?

1 个答案:

答案 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

SQL Fiddle Demo here

修改

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

SQL Fiddle Demo here