declare @date datetime,@yearFirstDay datetime,@lastYearDay datetime set @date='2012-1-1' --要计算其周次的日期 set @yearFirstDay=cast(DATEPART(year,@date) as CHAR(4))+'-1-1' --该年的1月1日 set @lastYearDay = cast(DATEPART(year,@date)-1 as CHAR(4))+'-12-31' --去年的12月31日
select case when DATEDIFF(WK,@yearFirstDay,@date) = 0 --如果正好是1月1日所在周,用去年最后一周的周次(一般是53) and DATEPART(DW,@yearFirstDay) > 1 --判断这一年的1月1号是不是周日(1表示周日,2表示周一。。。) then DATEPART(WK,@lastYearDay+'-12-31')--53
when DATEDIFF(WK,@yearFirstDay,@date) = 0 --如果是1月1号所在周 and DATEPART(DW,@yearFirstDay) = 1 --1月1日正好是周日,则为第一周 then 1 --第一周
when DATEDIFF(WK,@yearFirstDay,@date) > 0 --如果不是1月1号所在周 and DATEPART(DW,@yearFirstDay) = 1 --1月1日正好是周日,则为第一周 then DATEDIFF(WK,@yearFirstDay,@date)+1
else DATEDIFF(WK,@yearFirstDay,@date) --如果是,则1月1号所在周为第一周 end as week --否则,1月1号属于去年最后一周
System.Globalization.Calendar cal = new System.Globalization.CultureInfo("zh-CN").Calendar; int week = cal.GetWeekOfYear(countDay, System.Globalization.CalendarWeekRule.FirstFullWeek, System.DayOfWeek.Sunday);
declare @week int = datepart(ww, @d) - sign(datepart(dw,datename(year,@d))-1) if (@week=0) begin set @d -= datepart(dayofyear,@d) set @week = datepart(ww, @d) - sign(datepart(dw,datename(year,@d))-1) end select @week
[其他解释] 你想获取的是每一年的第一周是哪几天,对吧! [其他解释] 或者说给出一个日期,判断这个日期是这年的哪一周? [其他解释] declare @date date set @date='2013-1-5' select CONVERT(varchar(10),@date,23)+'为第'+cast(case when DATEPART(dw,cast(YEAR(@date) as CHAR(4))+'-1-1')<>1 then (case when DatePart(ww,@date)-1=0 then 53 else DatePart(ww,@date)-1 end) else DatePart(ww,@date) end as varchar(2))+'周' [其他解释]
[其他解释] 那还不简单 接着修改: declare @date date set @date='2013-1-5' select CONVERT(varchar(10),@date,23)+'为第'+cast(case when DATEPART(dw,cast(YEAR(@date) as CHAR(4))+'-1-1')<>1 then (case when DatePart(ww,@date)-1=0 then (DATEPART(dw,cast(YEAR(@date)-1 as CHAR(4))+'-12-31')) else DatePart(ww,@date)-1 end) else DatePart(ww,@date) end as varchar(2))+'周' 这次应该是终极版了,多谢楼上提醒。 [其他解释]