zoukankan      html  css  js  c++  java
  • 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
     
     
  • 相关阅读:
    Webpack 入门指迷--转载(题叶)
    浏览器工作原理理解
    Knockout.js初体验
    node.js链接mysql
    2020年度春季学习总结--第二周
    Python 爬取 热词并进行分类数据分析-[安全性改造]
    以 CheatEngine 为例的六个质量属性
    2020年度春季学习总结--第一周
    软件架构师如何工作-个人见解
    Steam 游戏 《Crashlands(崩溃大陆)》修改器制作-[先使用CE写,之后有时间的话改用CheatMaker](2020年寒假小目标12)
  • 原文地址:https://www.cnblogs.com/gyxianzg/p/12836322.html
Copyright © 2011-2022 走看看