SQL上一个日期记录

时间:2017-07-10 22:55:22

标签: sql sql-server tsql

我正在编写一个查询,该查询会返回最新和上个月数据的数据。

这里是数据库中的日期,每个月的日期可能不同(并不总是在1日发布)。所以,我需要拉最新的(最大)(2017-07-03和之前的日期2017-06-01)

filedate
2017-05-01
2017-06-01
2017-07-03

以下是我尝试的内容:

declare @filedate date = '2017-07-03'

select distinct max(filedate) filedate
from Table
where filedate = @filedate
order by filedate asc


select filedate
from Table
where filedate < (select min(@filedate) from Table)
group by filedate

和结果:

filedate (from the first query)
2017-07-03

filedate (from the second query)
2017-05-01
2017-06-01

4 个答案:

答案 0 :(得分:1)

这是一个神奇的问题:

SELECT DISTINCT TOP 2 filedate
FROM TABLE
ORDER BY filedate DESC

答案 1 :(得分:0)

如何选择前2名?像这样:

select top 2 filedate
from Table
order by filedate desc

答案 2 :(得分:0)

感谢@CuriousKid. ..这就是我为完成这项工作所做的工作。

declare @filedate date = (select max(filedate) from Table)  --'2017-07-03'

select distinct top 1 filedate as PriorDate
from Table
where filedate <> @filedate
order by filedate desc

答案 3 :(得分:0)

试试这个:

select max(filedate)from
(select '2017-05-01' as filedate union all
select '2017-06-01' union all
select '2017-04-10' union all
select '2017-07-03') as a where filedate<

(select max(filedate)from
(select '2017-05-01' as filedate union all
select '2017-06-01' union all
select '2017-04-10' union all
select '2017-07-03') as a limit 1)

union ALL

select max(filedate)from
(select '2017-05-01' as filedate union all
select '2017-06-01' union all
select '2017-04-10' union all
select '2017-07-03') as a 

结果:

2017-06-01
2017-07-03

您只需将示例数据替换为您的表名,如下所示:

select max(filedate)from
(select filedate from yourtable) as a where filedate<

(select max(filedate)from
(select filedate from yourtable) as a limit 1)

union ALL

select max(filedate)from
(select filedate from yourtable) as a