[英]Get max column with group by
I have a table for contents on a page. 我在页面上有一张内容表。 The page is divided into sections. 该页面分为多个部分。 I want to get the last version for each page-section. 我想为每个页面部分获取最新版本。
Id (int) Version (int) SectionID 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
I want to get: 我想得到:
Id Version SectionID Content 2 2 1 BBB 5 3 2 EEE
You could use an exclusive self join: 您可以使用排他的自我联接:
select last.*
from YourTable last
left join
YourTable new
on new.SectionID = last.SectionID
and new.Version > last.Version
where new.Id is null
The where
statement basically says: where there is no newer version of this row. where
语句基本上说:这里没有该行的较新版本。
Slightly more readable, but often slower, is a not exists
condition: not exists
条件稍微更具可读性,但通常更慢:
select *
from YourTable yt
where not exists
(
select *
from YourTable yt2
where yt2.SectionID = yt.SectionID
and yt2.Version > yt.Version
)
Example table definition: 表定义示例:
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');
Working solution: 工作解决方案:
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
A simpler and more readeable solution: 一个更简单,更易读的解决方案:
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
)
I just saw that there was a very similar question for Oracle with an accepted answer based on performance. 我刚刚看到对于Oracle有一个非常相似的问题 ,基于性能的答案是可以接受的。
Maybe if your table is big, an performance is an issue you can give it a try to see if SQL server also performs better with this: 也许如果您的表很大,则性能是一个问题,您可以尝试一下,看看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.