比如下面是摘自网上的代码:
DECLARE @DATE DATETIME = '2012-01-29' DECLARE @FIRST_DATE_OF_YEAR DATETIME = DATEADD(YYYY, DATEDIFF(YYYY, 0, @DATE), 0) SELECT DATEPART(WEEK, @DATE) , -- 一年中的周数,默认以周日开始 DATEADD(WK, DATEDIFF(WK, 0, @DATE), 0) , -- 当前周的周一,默认从周日开始,但是仍然找周一 DATEADD(DAY, -1, DATEADD(WK, DATEDIFF(WK, 0, @DATE), 0)) , -- 当前周先找周一,然后往前一天找到周日 DATEDIFF(DAYOFYEAR, @FIRST_DATE_OF_YEAR, DATEADD(DAY, -1, DATEADD(WK, DATEDIFF(WK, 0, @DATE), 0))) , -- 当前天离年第一天的间隔 DATEDIFF(DAYOFYEAR, @FIRST_DATE_OF_YEAR, DATEADD(DAY, -1, DATEADD(WK, DATEDIFF(WK, 0, @DATE), 0))) / 7 + 1 -- 按天计算的周数经过验证,发现写的是有问题的。。。
SELECT GETDATE() AS THEDAY, case when datepart(weekday,getdate()) in (2,3,4,5,6,7) then DATEPART(WEEK,GETDATE()) else DATEPART(WEEK,GETDATE()) -1 end AS WEEKS /* THEDAY WEEKS 2016-03-25 17:21:46.650 13 */
select getdate() as today, case when datepart(weekday,getdate()) in (2,3,4,5,6,7) and DATEPART(WEEKday,datename(year,getdate())+'-01-01') = 1 then datepart(week,getdate()) +1 when datepart(weekday,getdate()) =1 and DATEPART(WEEKday,datename(year,getdate())+'-01-01') = 1 then datepart(week,getdate()) when datepart(weekday,getdate()) in (2,3,4,5,6,7) then datepart(week,getdate()) else datepart(week,getdate()) -1 end as week /* today week 2016-03-28 18:56:30.747 14 */