我正在使用带有Microsoft SQL Server的VIsual Studio 2010,我正在尝试编写一个查询,该查询将按日期字段重新跟踪数据库中的(3)最新记录。以下是数据库中包含列的字段;
id | first_name | last_name |网址|日期
这是我正在使用的当前查询,但它只返回单个最近的条目;
SELECT id, first_name, last_name, url, MAX(DISTINCT date) AS Expr1
FROM tbl_paystubs
GROUP BY first_name
ORDER BY first_name
如何返回最近的(3)而不是(1)?
答案 0 :(得分:6)
您可以找到最大值,然后找到小于最大值的下一个日期,然后找到小于该最大值的下一个日期。使用CTE:
WITH firstDate(id, first_name, last_name, url, date)
as
(
SELECT id, first_name, last_name, url, MAX(DISTINCT date) AS Expr1
FROM tbl_paystubs
GROUP BY t.first_name, t.id, t.last_name, t.url
),
secondDate(id, first_name,Last_name,url,date)
(
SELECT t.id, t.first_name, t.last_name, t.url, MAX(t.date)
FROM tbl_paystubs t
inner join firstDate f
on f.id = t.id
and f.first_Name = t.first_name
and f.last_name = t.last_name
and f.url = t.url
WHERE f.date > t.date
GROUP BY t.first_name, t.id, t.last_name, t.url
),
thirdDate(id, first_name,Last_name,url,date)
(
SELECT t.id, t.first_name, t.last_name, t.url, MAX(t.date)
FROM tbl_paystubs t
inner join secondDate s
on s.id = t.id
and s.first_Name = t.first_name
and s.last_name = t.last_name
and s.url = t.url
WHERE s.date > t.date
GROUP BY t.first_name, t.id, t.last_name, t.url
)
select f.id,
f.first_name,
f.last_name,
f.url,
f.date as "FirstMax",
s.date as "SecondMax",
t.date as "ThirdMax"
from FirstDate f
left outer join SecondDate s
on f.id = s.id
and f.first_Name = s.first_name
and f.last_name = s.last_name
and f.url = s.url
left outer join ThirdDate t
on f.id = t.id
and f.first_Name = t.first_name
and f.last_name = t.last_name
and f.url = t.url
答案 1 :(得分:3)
尝试这样的事情:
SELECT TOP 3 id, first_name, last_name, url, date
FROM tbl_paystubs
ORDER BY date desc
答案 2 :(得分:2)
可以尝试
SELECT TOP 3 id, first_name, last_name, url, date
FROM tbl_paystubs
ORDER BY date desc
只是重新查看你的代码并注意到Max(日期),最好的事情要做,简单的事情就是订购并选择前3
答案 3 :(得分:0)
我的建议如下:
;with cte as(
SELECT *
,ROW_NUMBER() over (partition by [date] order by [date]) as seq
FROM tbl_paystubs
)
select Top 3 * from cte where seq= 1
CTE中的窗口函数,然后仅提取TOP 3记录
更新:我误解了这个问题,我认为OP正在寻找3个不同日期的3条记录。