简体   繁体   中英

How to compare records in same SQL Server table

在此处输入图片说明

My requirement is to compare each column of row with its previous row.

  1. Compare row 2 with row 1
  2. Compare row 3 with row 2

Also, if there is no difference, I need to make that column NULL. Eg: request_status_id of row 3 is same as that of row 2 so I need to update request_status_id of row 3 to NULL.

Is there a clean way to do this?

You can use the following UPDATE statement that employs LAG window function available from SQL Server 2012 onwards:

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

EDIT:

It seems the requirement of the OP is to SET every column of the table to NULL , in case the previous value is same as the current value. In this case the query becomes a bit more verbose. Here is an example with two columns being set. It can easily be expanded to incorporate any other column of the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM