zoukankan      html  css  js  c++  java
  • 计算工龄,以年月日形式显示

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

    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 的判断,都会出问题 

  • 相关阅读:
    os模块
    自定义模块--->可执行文件
    VSCode同步插件Sync
    Django之模板
    十:索引+慢查询
    八分组查询
    (一)Django之虚拟环境
    二:Anaconda的使用
    Python之数据类型
    Python零散知识点
  • 原文地址:https://www.cnblogs.com/gered/p/14857980.html
Copyright © 2011-2022 走看看