计算工龄,以年月日形式显示

需求,有个入职日期,以年月日形式显示该员工已经入职多久

复制代码
select 
case when datediff(year,date,getdate()) > 0  -- 如果当前年份大于入职年份
    then
    case when datepart(month,getdate()) - datepart(month,date)=0 -- 则 判断当前月份数字 与入职月份数字 相同
         then
            case when datepart(day,getdate()) - datepart(day,date)<0 -- 则 判断当前天数字是否 < 入职的天数字
                then datediff(year,date,getdate()) - 1   -- 如果是,则证明,虽然当前年份大于入职年份,但月份相同的情况,天数数字比入职时的少,所以年份差 -1
                else datediff(year,date,getdate())       -- 如果否,则证明,虽然当前年份大于入职年份,但月份相同的情况,天数数字比入职时的多,所以正常年份差
            end
    when datepart(month,getdate()) - datepart(month,date)<0  -- 二次判断,判断当前月份数字 比 入职月份数字小
        then datediff(year,date,getdate()) - 1    --如果是,则年份差 -1 ,比如 2020-08-01 入职,但现在是 2021-06-01,6-8<0,所以它们是没有差一年的,所以2021-2020的年份差需要再-1
    else datediff(year,date,getdate())     --如果否,则直接年份差,比如 2020-04-01 入职,但现在是 2021-06-01,6-4>=0,则直接 2021-2020 = 1 即可
    end 
else 0 end as 'year',

-- 下述都一样,就不一一赘述,参考上面的年份即可
case when datepart(month,getdate()) - datepart(month,date)=0 
     then
          case when datepart(day,getdate()) - datepart(day,date)<0 
               then datepart(month,getdate())+12 - datepart(month,date) -1
          else datepart(month,getdate()) - datepart(month,date)
          end
when datepart(month,getdate()) - datepart(month,date)<0 
     then 
         case when datepart(day,getdate()) - datepart(day,date)<0 
                   then datepart(month,getdate())+12 - datepart(month,date) -1
              else datepart(month,getdate())+12 - datepart(month,date)
         end
else datepart(month,getdate()) - datepart(month,date) 
end as 'month',

case when datepart(day,getdate()) - datepart(day,date)<0 
     then 
          case when (datepart(month,getdate())-1) in (1,3,5,7,8,10,12)
               then datepart(day,getdate())+31 - datepart(day,date)
          else datepart(day,getdate())+30 - datepart(day,date)
          end
     else datepart(day,getdate()) - datepart(day,date)
end as 'day'

from (
select cast('2020-06-12' as datetime) as date union all
select cast('2020-08-11' as datetime) union all
select cast('2018-06-01' as datetime) union all
select cast('2018-05-07' as datetime) union all
select cast('2020-12-08' as datetime) union all
select cast('2020-11-06' as datetime) union all
select cast('2019-09-08' as datetime)

) t
复制代码

  

缺陷,还没有包含进闰年,所以在2月的时候,特别是 28-29  29-28 的判断,都会出问题 

 

posted @   郭大侠1  阅读(492)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示