获取分组依据的最大列

时间:2010-07-22 14:52:09

标签: sql sql-server-2005

我在页面上有一个内容表。该页面分为几个部分。 我想获得每个页面部分的最新版本。

Id(int) 版本(int) SectionID

Id    Version    SectionID    Content
1       1           1           AAA
2       2           1           BBB
3       1           2           CCC
4       2           2           DDD
5       3           2           EEE

我想得到:

Id    Version    SectionID    Content
2       2           1           BBB
5       3           2           EEE

4 个答案:

答案 0 :(得分:1)

您可以使用独家自助加入:

select  last.*
from    YourTable last
left join
        YourTable new
on      new.SectionID = last.SectionID
        and new.Version > last.Version
where   new.Id is null

where语句基本上表示:此行没有更新版本。

稍微更具可读性,但通常更慢,是not exists条件:

select  *
from    YourTable yt
where   not exists
        (
        select  *
        from    YourTable yt2
        where   yt2.SectionID = yt.SectionID
                and yt2.Version > yt.Version
        )

答案 1 :(得分:1)

示例表定义:

declare @t table(Id int, [Version] int, [SectionID] int, Content varchar(50))

insert into @t values (1,1,1,'AAA');
insert into @t values (2,2,1,'BBB');
insert into @t values (3,1,2,'CCC');
insert into @t values (4,2,2,'DDD');
insert into @t values (5,3,2,'EEE');

工作解决方案:

select A.Id, A.[Version], A.SectionID, A.Content
from @t as A
join (
    select max(C.[Version]) [Version], C.SectionID
    from @t C
    group by C.SectionID
) as B on A.[Version] = B.[Version] and A.SectionID = B.SectionID
order by A.SectionID

答案 2 :(得分:1)

更简单,更易读的解决方案:

select A.Id, A.[Version], A.SectionID, A.Content
from @t as A
where A.[Version] = (
    select max(B.[Version])
    from @t B
    where A.SectionID = B.SectionID
)

答案 3 :(得分:0)

我刚看到Oracle有一个very similar question,根据性能确定了答案。

也许如果你的表很大,性能是一个问题你可以尝试看看SQL服务器是否也表现更好:

select Id, Version, SectionID, Content
from (
    select Id, Version, SectionID, Content,
           max(Version) over (partition by SectionID) max_Version
    from   @t
) A
where Version = max_Version