繁体   English   中英

通过分组获取最大列

[英]Get max column with group by

我在页面上有一张内容表。 该页面分为多个部分。 我想为每个页面部分获取最新版本。

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

您可以使用排他的自我联接:

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
        )

表定义示例:

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

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

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
)

我刚刚看到对于Oracle有一个非常相似的问题 ,基于性能的答案是可以接受的。

也许如果您的表很大,则性能是一个问题,您可以尝试一下,看看SQL Server在此方面是否也表现更好:

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

暂无
暂无

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

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