SQL Server中以星期一为每周第一天 计算周数

SQL Server中以星期一为每周第一天 计算周数,但是在网上搜了,看了一些,写的都挺复杂,一堆的sql代码,但是实际运行了一下,都是不对的。。。

比如下面是摘自网上的代码:

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
*/

你可能感兴趣的:(SQL Server中以星期一为每周第一天 计算周数)