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