如果问题很愚蠢,我很抱歉,因为我是SQL Server的新手。我想为指定月份的每一天选择前5个记录。 例如
top 5 records for day 1 in month september
top 5 records for day 2 in month september
top 5 records for day 3 in month september
.
.
top 5 records for day 31 in month september
并将所有记录显示为一个结果。
答案 0 :(得分:3)
假设你正在检查2012年6月的超速记录,你想要前5个速度(按速度desc
)。
SELECT *
FROM (
SELECT *, RowNum = Row_number() over (partition by Cast(EventTime as Date)
order by Speed desc)
FROM Events
WHERE EventTime >= '20120601'
AND EventTime < '20120701'
) X
WHERE RowNum <= 5
答案 1 :(得分:1)
试试这个,
WITH TopFiveRecords
AS
(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY dayColumn ORDER BY colName DESC) RN
FROM tableName
)
SELECT *
FROM TopFiveRecords
WHERE RN <= 5
-- AND date condition here ....
dayColumn
包含月份日期的列
colName
要排序的列