当前位置: 移动技术网 > IT编程>数据库>MSSQL > sql某个日期是当年的第几周

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

2020年05月07日  | 移动技术网IT编程  | 我要评论

底漆面漆,孤芳不自赏开机路透照曝光,北京人社局

/*
*周一作为一周的开始
*当年的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
 
 

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网