简体   繁体   English

SQL查询以查找最新记录组

[英]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 . 我有一个共享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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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