简体   繁体   中英

SQL Query to find the most recent group of records

I have a history of records (multiple records per update all with the exact same datetime) that share an IdString .

I want a query to determine which of these records are part of the most recent update group.

This query will show me one of the records having the most recent update date, but for each partition, I need all the records with that max date .

;with cte as(
select ROW_NUMBER() over (partition by IdString order by UpdateDate desc) as [rn], *
from MyTable
)
select  CASE WHEN (cte.rn = 1) THEN 0 ELSE 1 END [IsOld], *
from MyTable m
inner join cte on cte.RecordId= m.RecordId

Would someone please help me figure out an appropriate query?

EDIT: Sample

(IsOld is the desired calculated value)

IsOld RecordId  IdString  UpdateDate
1         1     ABC 2011-06-16 
1         2     ABC 2012-05-30 
1         3     ABC 2008-12-31 
0         4     ABC 2012-06-08 
1         5     ABC 2011-01-16 
0         6     ABC 2012-06-08 
1         7     ABC 2012-06-07 
1         8     XYZ 2001-01-16
1         9     XYZ 2013-01-30
0         10    XYZ 2001-01-31
1         11    XYZ 2013-06-01
1         12    XYZ 2001-05-04
0         13    XYZ 2013-01-30
SELECT CASE WHEN updateDate = maxDate THEN 0 ELSE 1 END isOldRecord, RecordID, IDString, UpdateDate
FROM 
(
select  m.RecordID, m.IDString, m.updateDate, MAX(UpdateDate) OVER (PARTITION BY IDString) maxDate
    from MyTable m
) A

Try this -

;WITH cte AS(
    SELECT RANK() OVER(PARTITION BY IdString ORDER BY UpdateDate DESC) AS [row_num], *
    FROM   MyTable
)
SELECT CASE WHEN m.[row_num] = 1 THEN 0 ELSE 1 END isOld, *
from cte m

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