如何在SQL中获取最新的日期? [英] How can I get the most recent date in SQL?

查看:928
本文介绍了如何在SQL中获取最新的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个SQL查询,从日期列获取日期和最近的日期。因此,如果我的数据库中有三条记录有以下日期:

I want to make a SQL query that gets todays date and the most recent date from a date column. So if I have three records in my database that have the following dates:


  • 2012年3月8日

  • 2012年3月2日

  • 2011年12月8日

我希望SQL查询返回2012年3月8日和2012年3月2日的所有记录(最近的日期)。我可以这样做吗?

I want the SQL query to return all records for March 8, 2012 and March 2, 2012 (most recent date). How can I do this?

我可以在日期的日期使用:

I can date today's date using:

CONVERT( varchar(100), DATEADD( DAY, 0, getdate() ), 111)

谢谢

编辑:
感谢大家。我还有一个问题。我创建了两个视图:

Thanks everyone. I just have one more question. I have created two views:

create view with top dates
CREATE VIEW topDates AS
select DISTINCT TOP 3 replace(CONVERT(VARCHAR(20),date,111),'-','/') AS dates from     CSAResults.dbo.Details

create view dateTwo
select *
from (select ROW_NUMBER() over (order by dates desc) as srNo, dates
    from topDates)
    AS employee
    WHERE srNo=2

现在我想从我的数据库中选择*,其中列等于视图'dateTwo'的'dates'列

And now I want to select * from my DB where a column is equal to the 'dates' column from the view 'dateTwo'

select buildNumber
from CSAResults.dbo.Details
where buildNumber LIKE '%Main '+ (SELECT dates FROM dateTwo) + '%'

但这不返回任何东西。

谢谢

推荐答案

您可以执行以下操作:

select date
from yourtable
where 
(
    date = Convert(varchar(10), getdate(), 101)
    OR
    date IN (SELECT Max(date) 
                FROM yourtable
                WHERE date!= Convert(varchar(10), getdate(), 101))
)

这篇关于如何在SQL中获取最新的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆