• sql某个日期是当年的第几周


    /*
    *周一作为一周的开始
    *当年的1月1号所在的周算作第一周
    */
    CREATE function GetWeekIndexFirstDate
    (
       @date datetime
    )
    returns int
    as
    begin
     
    /*
    *计算逻辑
    *1.先找出当年的1月1号@firstDate
    *2.计算出当年的第一个周日@firstSunday
    *3.以@firstSunday为分界线,@firstSunday前面的算作第一周,@firstSunday后面的通过除7再加1,来计算周数
    */
     
       declare @index int;
       declare @firstDate datetime;--当年的1月1号
       declare @firstSunday datetime;--当年的第一个周日
       declare @firstWeekSunday datetime;--当年的第一周的周日
     
       set @firstDate = convert(datetime,convert(varchar(4),Year(@date)) + '-1-1')
     
       set @firstSunday = case when datepart(dw,@firstDate)=1 then @firstDate else dateadd(dd,8-datepart(dw,@firstDate),@firstDate) end;
     
       if(@date<=@firstSunday)
          set  @index = 1;
       else
          set @index = ceiling(datediff(dd,@firstSunday,@date)/7.0)+1
     
       return @index;
    end
    
    
    
     
     
    /*
    *周一作为一周的开始
    *当年的第一个周一所在的周算作第一周
    */
    CREATE function GetWeekIndexFirstMonday
    (
       @date datetime
    )
    returns int
    as
    begin
     
     
     
    /*
    *计算逻辑
    *1.先找出当年的1月1号@firstDate
    *2.计算出当年的第一个周一@firstMonday
    *3.以@firstMonday为分界线,@firstMonday前面的算作上一年的最后一周,@firstMonday后面的通过除7再加1,来计算周数
    */
     
       declare @index int;
       declare @firstDate datetime;--当年的1月1号
       declare @firstMonday datetime;--当年的第一个周一
       declare @lastYearFirstDate datetime;--上一年的1月1号
       declare @lastYearFirstMonday datetime;--上一年的第一个周一
     
       select @firstDate = convert(datetime,convert(varchar(4),Year(@date)) + '-1-1')
          , @lastYearFirstDate = convert(datetime,convert(varchar(4),datepart(yyyy,@date)-1) + '-1-1')
     
       select @firstMonday = case when datepart(dw,@firstDate)<=2 then dateadd(dd,2-datepart(dw,@firstDate) ,@firstDate)
                          else dateadd(dd,9-datepart(dw,@firstDate),@firstDate) end
          ,@lastYearFirstMonday = case when datepart(dw,@lastYearFirstDate)<=2 then dateadd(dd,2-datepart(dw,@lastYearFirstDate) ,@lastYearFirstDate)
                          else dateadd(dd,9-datepart(dw,@lastYearFirstDate),@lastYearFirstDate) end;
     
    
    
    
       if(@date >=@firstMonday)
          set  @index = floor(datediff(dd,@firstMonday,@date)/7.0)+1;
       else
          set @index = floor(datediff(dd,@lastYearFirstMonday,@date)/7.0)+1
     
       return @index;
    end
     
     
  • 相关阅读:
    设计模式-外观模式
    发生死锁怎么办
    设计模式-工厂模式
    设计模式-模板方法
    设计模式-命令模式(Command)
    设计模式-单例模式
    设计模式-装饰器模式
    CQRS之旅——旅程8(后记:经验教训)
    CQRS之旅——旅程7(增加弹性和优化性能)
    CQRS之旅——旅程6(我们系统的版本管理)
  • 原文地址:https://www.cnblogs.com/gyxianzg/p/12836322.html
Copyright © 2020-2023  润新知