Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all scores for the 2nd to most recent date

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).

like image 291
dmr Avatar asked Dec 09 '25 02:12

dmr


1 Answers

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
like image 180
Alex Aza Avatar answered Dec 10 '25 16:12

Alex Aza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!