sql - 查找第 2 天到最近日期的所有分数

标签 sql sql-server tsql sql-server-2000

我有一个历史记录表,其中包含每个日期每个组的分数(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/

相关文章:

C# 字符串和 VARCHAR 和 NVARCHAR

SQL 连接加倍一些输出

sql-server - "Null"值在 SQL Server 中占用多少大小

sql-server - 无法从 ubuntu 连接到 azure sql server

sql - 检查列值是否为零 MS SQL Server

sql - 选择 bigquery 中除一列以外的所有列

sql - 数据库事务——或者这是一个规范化问题?

mysql - 如何更新MYSQL数据库所有表的公共(public)字段长度?

sql - 如何从三个独立的表构建事件表,显示随时间的增量变化?

c# - 存储在数据库中时图像的大小