Sqlserver
 sql >> Base de Dados >  >> RDS >> Sqlserver

SQL se o registro for igual ao registro antes dele

;WITH MyCTE AS
(
    SELECT *, 
           ROW_NUMBER()OVER (ORDER BY TextString) AS rn
    FROM   Table1
)
SELECT T1.TextString AS T1String,
       T2.TextString AS T2String,
       CASE WHEN T1.TextString = T2.TextString THEN T1.ID ELSE '' END AS NewCode,
       CASE WHEN T1.TextString = T2.TextString THEN T2.ID ELSE '' END AS OldCode
FROM   MyCTE T1
       LEFT JOIN MyCTE T2
           ON T1.rn = T2.rn+1

Demonstração do SQL Fiddle