Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Come eliminare i reclami con ClaimStatus =1 in base alla data dell'attività. SQL Server 2012

DEMO SQL

WITH cte as (
    SELECT ClaimNumber, 
           ClaimStatus,
           ROW_NUMBER() over (PARTITION BY ClaimNumber ORDER BY ActivityDate DESC) as rn
    FROM @TempTable
)
SELECT t.*
FROM @TempTable t
JOIN (SELECT *
      FROM cte
      WHERE rn = 1) f
  ON t.ClaimNumber = f.ClaimNumber
 AND f.ClaimStatus = 0

USCITA

Inoltre, se solo 2 stati puoi anche fare

WITH cte as (
    SELECT ClaimNumber
    FROM @TempTable
    GROUP BY ClaimNumber
    HAVING MAX(ClaimStatus) = 0
)
SELECT t.*
FROM @TempTable t
WHERE ClaimNumber IN (SELECT * FROM cte)