2011-12-28 37 views
1

如何找到datetime列中最古老的值?找出從日期列中的舊日期在sql

我有日期時間列(UpdateDate)表,我需要找出最早的數據基於UpdateDate。

Id  UpdateDate     Desc 
----------------------------------------- 
1 2010-06-15 00:00:00.000  aaaaa 
2 2009-03-22 00:00:00.000  bbbbb 
3 2008-01-12 00:00:00.000  ccccc 
4 2008-02-12 00:00:00.000  ddddd 
5 2009-04-03 00:00:00.000  eeeee 
6 2010-06-12 00:00:00.000  fffff 

我必須找出使用 Select UpdateDate from Table1 where DATEDIFF(YEAR,UpdateDate,getdate()) > 0查詢當前日期的舊年的日期。但我需要找出2008年的數據(因爲2008年是這裏最老的一個) 我不知道表中有什麼,我需要找出最舊的日期值。它怎麼可能?

回答

3
Select UpdateDate from Table1 where DATEDIFF(YEAR,PartDateCol,getdate()) IN 
(Select MAX(DATEDIFF(YEAR,PartDateCol,GETDATE())) DiffYear from Table1) 

此發現的最古老的日期將返回2008年的兩項紀錄。如果你的紀錄有四項2006年的紀錄如果差別很大,它將返回所有2006年的數據。

+0

雅...這是我的預期..感謝很多傢伙.. :-) – Tanya 2011-12-28 07:21:29

0

如果你想要的數據,2008年一年內嘗試這個辦法:

Select UpdateDate From Table1 
Where Year(UpdateDate) = 
(
    Select Year(UpdateDate) 
    from Table1 Order By UpdateDate ASC Limit 1 
) ; 
+0

感謝您的回覆..但我需要的是,我不知道2008年是否是最古老的。我只知道表名,它包含一些日期值,因此我需要找出最早的日期。 – Tanya 2011-12-28 07:16:43

+0

@Tanya固定,看我的編輯。 – 2011-12-28 08:13:18

0

您可以使用toporder by

select top(1) UpdateDate 
from Table1 
order by UpdateDate 

更新:

如果你想第一年現在你可以使用它代替了所有行。這樣做的

select * 
from (
     select *, 
      rank() over(order by year(UpdateDate)) as rn 
     from Table1 
    ) as T 
where T.rn = 1 
0

一種方法是

Select UpdateDate from Table1 where YEAR(UpdateDate)=2008

但是,你可以通過訂購數據,這樣

Select * from Table1 order by UpdateDate ASC