2012-03-06 63 views
0

表1如何找到最近的生日

ID Dateofbirth 

001 01/01/1988 'dd/mm/yyyy 
002 01/05/2001 
.... 

從表1,我想找到最近的每個ID的生日。最近的生日應該用系統日期進行驗證。

預期輸出

ID Dateofbirth MostRecentBirthday 

001 01/01/1988 01/01/2012 
002 01/05/2001 01/05/2011 
.... 

輸出中解釋

For 001, most recent birthday is 01/01/2012 
For 002, most recent birthday is 01/05/2011 ' because still we are not reached this date 01/05/2012 
+0

列數據類型是DateTime還是VARCHAR? – Seph 2012-03-06 06:07:39

+0

閏日呢?你想怎麼處理? – 2012-03-06 07:23:13

回答

3

來回答前面的問題類似:

select ID, 
     Dateofbirth, 
     dateadd(yy, 
       datediff(yy,Dateofbirth,getdate()) - 
          case when dateadd(yy,datediff(yy,Dateofbirth,getdate()),Dateofbirth)>getdate() 
          then 1 else 0 end, 
       Dateofbirth) MostRecentBirthday 
from ... 
0

假設列類型是DATE(或DATETIME):

SELECT id, 
     Dateofbirth, 
     CONVERT(date, 
     DATEPART(month, Dateofbirth) + '/' 
     + DATEPART(day, Dateofbirth) + '/' 
     + CASE WHEN DATEPART(month, Dateofbirth) < DATEPART(month, GETDATE()) OR 
        (DATEPART(month, Dateofbirth) = DATEPART(month, GETDATE()) AND DATEPART(day, Dateofbirth) < DATEPART(day, GETDATE())) 
       THEN DATEPART(year, GETDATE()) 
       ELSE DATEPART(year, GETDATE())-1 
     END, 
     101) AS MostRecentBirthday 
FROM your_table 

沒有測試,但是應該很接近。

0

如果使用Age UDF,那麼查詢可以簡單地是:

SELECT 
    ID, 
    Dateofbirth, 
    DATEADD(year, dbo.Age(Dateofbirth), Dateofbirth) AS MostRecentBirthday 
FROM 
    ... 
0

這樣的想法可以幫助

SELECT 
    ID, 
    dateofbirth, 
    convert(nvarchar(10), day(dateofbirth)) + "/" + 
    convert(nvarchar(10), month(dateofbirth)) + 
    CASE month(getdate()) > Month(dateofbirth) 
    WHEN TRUE THEN convert(nvarchar(10), year(getdate())) 
      ELSE CASE month(getdate()) < Month(dateofbirth) 
       WHEN TRUE THEN convert(nvarchar(10), Year(getdate())-1) 
         ELSE CASE day(getdate()) >= day(dateofbirth) 
            WHEN TRUE THEN Year(getdate()) 
            ELSE Year(getdate())-1) 
            END 
         END 
      END MostRecentBirthday 
FROM .....