我有一个页面上的内容表。该页面分为几个部分。 我想获取每个页面部分的最后一个版本。通过组获得最大列
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
我有一个页面上的内容表。该页面分为几个部分。 我想获取每个页面部分的最后一个版本。通过组获得最大列
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
+ 1为便利的表定义:) – Andomar 2010-07-22 15:50:04
更简单和更readeable解决方案:
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
)
这看起来像这样做的最'正常'的SQL方式我。 Andomar与关系运算符的方法同样合乎逻辑,但似乎比使用max更挑剔。显式连接的查询基本上与此相同,但这更简洁。你从Oracle人员那里得到的查询每隔一行返回一个max_Version就是可怕的 - 我不怀疑它有效,但它冒犯了我的眼睛! – 2010-07-23 17:00:46
我刚刚看到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
第一个解决方案是行不通的。我不明白你为什么'where'说'id是空'? – 2010-07-22 15:29:02
@Protron:在连接条件中错过了'和',现在添加。 'left join'搜索比'last'中的行更新的行。 where子句说新行不能存在(如果'left join'找不到匹配项,'new.Id'为空。] – Andomar 2010-07-22 15:44:21
它对我有用! =)谢谢! – Shay 2010-07-22 15:49:49