找到第二个到最近日期的所有分数。

| 我有一个历史记录表,其中包含每个日期每个组的得分(PK是组,日期)。 SQL查询可以检索最近第二个日期所有组的分数的SQL查询是什么? 预计到达时间:各组的日期相同(每个组的得分均同时输入到历史记录表中)。     
已邀请:
        
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
    
        您需要两个聚合 获取每个组的最大日期 获取每个组的最大日期,该日期小于步骤1中的日期 加入该汇总中的分数 就像是
SELECT
    Group, Date, Score
FROM
    ( ..2nd max date per group
    SELECT
       Group, MAX(Date) AS TakeMe
    FROM
        ( --max date per group
        SELECT
           Group, MAX(Date) AS IgnoreMe
        FROM
           MyTable
        GROUP BY
           Group
        ) ex
        JOIN
        MyTable M ON ex.Group = M.Group AND ex.IgnoreMe > M.Date
    GROUP BY
        M.Group
    ) inc
    JOIN
    MyTable M2 ON inc.Group = M2.Group AND inc.TakeMe = M2.Date
在带有ROW_NUMBER()的SQL Server 2005上,这非常容易...     
        
SELECT *
FROM tblScore
WHERE EXISTS
(
    SELECT NULL
    FROM tblScore as tblOuter
    WHERE NOT EXISTS
    (
        SELECT NULL
        FROM tblScore As tblInner
        WHERE tblInner.[group] = tblOuter.[group]
        GROUP BY [group]
        HAVING MAX(tblInner.[date]) = tblOuter.[date]
    ) 
    AND tblOuter.[group] = tblScore.[group]
    GROUP BY [group]
    HAVING MAX(tblOuter.[date]) = tblScore.[date]
)
    
        尝试这个。我正在尝试首先获取
TOP 2 DISTINCT
Dates Desc,如果您仅使用日期而不是datetimes,它将起作用。然后反转该表并获得
TOP 1
,并将该结果用作最近的第二个日期以获取组得分。
SELECT *
FROM YourTable
INNER JOIN 
(SELECT TOP 1 x.[date]
FROM
    (SELECT TOP 2 DISTINCT [date]
    FROM YourTable
    ORDER BY [date] DESC) AS x
ORDER BY [date] ASC) AS y
ON y.[date] = YourTable.[date]
我认为这可能需要8英镑,但我不确定     

要回复问题请先登录注册