基于下表
Table_A
ID Rev Description
-----------------------------------
1 1 Some text.
1 2 Some text. Adding more.
1 3 Some text. Ading more & more.
当用户更新描述时,上面将继续添加新行.
我想用MAX(Rev)取行[即最新描述].
为此,我执行以下操作:
;with AllDescriptions As
(
select
ID
, Rev
, Description
, ROW_NUMBER() over (partition by ID order by Rev desc) as RowNum
from Table_A
Where ID = 1
)
select ID, Rev, Description from AllDescription
where RowNum = 1
最近我看到了一种不同的方法来获得相同的结果
select b.* from
(
select ID, MAX(Rev) as MaxRev
from Table_A
where ID = 1
group by ID
) as a
inner join
(
select ID, Rev, Description from Table_A where ID = 1
) as b
on a.ID = b.ID and a.MaxRev = b.Rev
从学习的角度来看,我想知道上述哪两种方法更好?或者,如果有更好的方法来做同样的事情?
最佳答案 在引入Row_Number()之前,第二种方法看起来像SQL Server 2000方法.这是
Greatest-n-per-group problem.
要评估它们,您应该通过运行SET STATISTICS IO ON来查看执行计划和I / O统计信息
当然,对于您给出以下内容的具体示例,同样可以正常工作
select TOP 1
ID
, Rev
, Description
from Table_A
Where ID = 1
ORDER BY Rev desc