简体   繁体   English

计算Sql中日期之间的年数

[英]Calculate Number of years between dates in Sql

I need to calculate the number of complete years between two dates in sql. 我需要计算sql中两个日期之间的完整年数。 The query I am using currently to calculate is 我目前用来计算的查询是

--Date1 > Date2
CASE
WHEN YEAR(Date1) = YEAR(Date2)
    THEN DATEDIFF(year, Date2, Date1)
WHEN YEAR(Date1) > YEAR(Date2) 
        AND MONTH(Date1) >= MONTH(Date2)
        AND DAY(Date1) >= DAY(Date2)
    THEN DATEDIFF(year, Date2, Date1)
ELSE
    DATEDIFF(year, Date2, Date1) - 1

However I need to tweak it somehow so that it considers the time between 1/5/2011 and 30/4/2012 as 1 complete year. 但是我需要以某种方式调整它,以便它将2011年1月5日到2012年4月30日之间的时间视为1整年。

在比较之前将一天添加到Date2

dateadd(day, 1, Date2)

If the goal is to consider 1-year-less-a-day to be a full year, what about simply adding 1 day to your later date? 如果我们的目标是将一年的一年减少考虑为一年,那么只需将1天添加到您以后的日期即可? dateadd() should do it. dateadd()应该这样做。

mysql> SELECT ADDDATE('2011-05-01', INTERVAL 1 DAY);
        -> '2011-05-02'

I don't think that would cause other erroneous calculations... 认为这不会导致其他错误的计算......

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

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