如何从返回记录集中选择最新记录?

时间:2012-12-26 05:25:28

标签: sql sql-server-2008

我在SQL Server 2008中有SQL表,我希望得到最新的记录,这取决于它的日期。

E.g。假设我有一些列和一个Date列的记录,其中包含创建记录的日期。 让我们坐在日期列包含以下日期。 12月22日,12月23日,12月24日,12月25日,12月26日 - 12月。

现在,我想获取小于25月12日的记录,但我想要最新的日期记录,如果我写了查询

select * from Table where CreateDate < '25-Dec-2012' 

那么它将返回3条记录,但我想要他们的最新记录,即12月24日记录

怎么做?

7 个答案:

答案 0 :(得分:1)

您应该在查询中添加TOP 1,并按照其自然顺序进行排序,以便先获取最后一条记录。假设默认顺序是CreateDate按升序排列,ORDER BY CreateDate DESC应该可以解决问题:

SELECT TOP 1 *
FROM Table
WHERE CreateDate < '25-Dec-2012' 
ORDER BY CreateDate DESC

答案 1 :(得分:1)

使用此功能,可以正常使用,手动检查.. :)

select top 1 * 
from TableName 
where Createdate < '25-Dec-2012' 
order by Createdate desc

答案 2 :(得分:0)

请尝试:

select 
  top 1 * 
from Table 
  where CreateDate < '25-Dec-2012' 
order by CreateDate desc

答案 3 :(得分:0)

使用TOP

SELECT TOP 1 *
FROM TABLENAME
WHERE CreateDate < '25-Dec-2012'
ORDER BY CreateDate DESC

答案 4 :(得分:0)

你可以将“Top”包括为..

    select top 1 * from Table where CreateDate < '25-Dec-2012' order by CreateDate desc;

答案 5 :(得分:0)

OP表示每个日期只有一行,因此2012年12月24日的行将是所需的行。

select * from Table where CreateDate = '24-Dec-2012'

答案 6 :(得分:-1)

您必须使用orderlimit

select * from Table where CreateDate < '25-Dec-2012'  order by CreateDate DESC LIMIT 1
相关问题