I have a history table that contains a score per group per date (PK is group, date). What is the SQL query that can retrieve the scores for all groups for the 2nd most recent date?
ETA: The dates are the same across groups (each score is entered into the history table at the same time for each group).
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
)
Setup:
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'
The query would looks as simple as below for 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With