我有一个历史记录表,其中包含每个日期每组的分数(PK是组,日期)。什么是可以检索第二个最近日期的所有组的分数的SQL查询?
ETA:各组的日期相同(每个组的每个分数同时输入到历史记录表中)。
答案 0 :(得分:4)
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 :(得分:3)
您需要两个聚合
像
这样的东西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上 更容易 ...
答案 2 :(得分:2)
试试这个。我想首先获得TOP 2 DISTINCT
日期描述,如果您只使用日期而不是日期时间,那将会有效。然后反转该表并获取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]
我认为这可能需要WHERE y.date = YourTable.date
,但我不确定
答案 3 :(得分:2)
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]
)