0

我有共享一个IdString.

我想要一个查询来确定这些记录中的哪些是最近更新组的一部分。

此查询将向我显示具有最近更新日期的记录之一,但对于每个分区,我需要具有该 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

有人可以帮我找出一个合适的查询吗?

编辑:样本

(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
4

2 回答 2

2
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
于 2013-10-21T21:37:20.287 回答
1

尝试这个 -

;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
于 2013-10-21T23:26:24.997 回答