我有一个历史记录表,其中包含每个日期每个组的分数(PK 是组、日期)。可以检索最近第二个日期的所有组的分数的 SQL 查询是什么?
ETA:各组的日期相同(每个组的每个分数同时输入到历史表中)。
最佳答案
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
关于sql - 查找第 2 天到最近日期的所有分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6346643/