select *
from ScoreHistory sc1
where exists
(
select GroupId, max(ScoreDate) RecentScoreDate
from ScoreHistory sc2
where not exists
(
select GroupId, max(ScoreDate) RecentScoreDate
from ScoreHistory sc3
group by GroupId
having GroupId = sc2.GroupId and max(ScoreDate) = sc2.ScoreDate
)
group by GroupId
having GroupId = sc1.GroupId and max(ScoreDate) = sc1.ScoreDate
)
Установка:
create table ScoreHistory(GroupId int, ScoreDate datetime)
insert ScoreHistory
select 1, '2011-06-14' union all
select 1, '2011-06-15' union all
select 1, '2011-06-16' union all
select 2, '2011-06-15' union all
select 2, '2011-06-16' union all
select 2, '2011-06-17'
Запрос будет выглядеть так же просто, как показано ниже для MS SQL 2005 +
;with cte
as
(
select *, row_number() over(partition by GroupId order by ScoreDate desc) RowNumber
from ScoreHistory
)
select *
from cte
where RowNumber = 2