简体   繁体   English

如何找到确切的年和日

[英]How to find the exact years and days

Table

id date-of-birth

001 01/01/2011 'dd/mm/yyyy'
002 05/01/2012
003 15/05/2009
....

From the above table, i want to calculate number of days from date-of-join column, date-of-birth should be validate from current year. 从上表中,我想从加入日期列中计算天数,出生日期应从当年开始验证。

Finding the date difference query 查找日期差异查询

Select id, DATEDIFF(dd,Convert(datetime, date-of-join, 103),getdate())

the above query is working from date-of-join, but ii want to validate the date-of-join like this... 上面的查询从加入日期开始工作,但是ii要像这样验证加入日期...

For example 例如

id date-of-birth no-of-days

001 01/01/2011   64 
002 05/01/2012   60
003 15/05/2009   295

.... ....

Conditions 条件

For 001, date-of-birth is '01/01/2011', so one year exceeded, then it should give no-0f-days from '01/01/2012'

For 002, date-of-birth is '05/01/2012, so it is not exceeded one years, then it should give no-of-days from '05/01/2012'

For 003, date-of-birth is '15/05/2009', so it is exceeded more than a years, then it should calculate from 15/05/2011 to current date 

Can any one give some ideas or query help 任何人都可以提出想法或查询帮助吗

Try: 尝试:

select id,
       [date-of-birth],
       datediff(yy,[date-of-birth],getdate()) -
                   case when dateadd(yy,datediff(yy,[date-of-birth],getdate()),[date-of-birth])>getdate()
                   then 1 else 0 end as [no-of-years],
       datediff(d,
                dateadd(yy,datediff(yy,[date-of-birth],getdate()) -
                           case when dateadd(yy,datediff(yy,[date-of-birth],getdate()),[date-of-birth])>getdate()
                           then 1 else 0 end,[date-of-birth]),
                getdate()) as [no-of-days]
from ...
declare @T table (id int identity(100,1), date datetime)
insert @T values('2012-05-01')
insert @T values('2012-03-1')
insert @T values('2011-01-01')
insert @T values('2009-05-15')
insert @T values('2008-01-23')

select 
    id,
    date,
    Days = case when datediff(dd,date,getdate())>730 
                    then datediff(dd,date,getdate()) - (datediff(dd,date,getdate())/365 * 365)
                when datediff(dd,date,getdate())>365 
                    then datediff(dd,convert(datetime, datename(yy,getdate()) + '/01/01'),getdate()) 
               else abs(datediff(dd,date,getdate()))
           end
from @T

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM