请注意,根据文化的不同,正确的周数会有所不同.周数取决于几个国家/地区不同的假设,请参阅Wikipedia关于此事的文章.有一个ISO标准,适用于周数(ISO 8601).
SQL Server集成DATEPART()
功能不一定做正确的事情.对于许多错误的应用程序,SQL Server假定第1周的第1天将是1月1日.
正确计算周数非常重要,可以在网上找到不同的实现.例如,有一个UDF可以计算1930年至2030年间的ISO周数,是其中之一.你必须检查什么对你有用.
这个来自联机丛书(虽然你可能想使用Jonas Lincoln的回答,BOL版本似乎不正确):
CREATE FUNCTION ISOweek (@DATE DATETIME) RETURNS INT AS BEGIN DECLARE @ISOweek INT SET @ISOweek = DATEPART(wk,@DATE) +1 -DATEPART(wk,CAST(DATEPART(yy,@DATE) AS CHAR(4))+'0104') -- Special cases: Jan 1-3 may belong to the previous year IF (@ISOweek=0) SET @ISOweek = dbo.ISOweek(CAST(DATEPART(yy,@DATE) - 1 AS CHAR(4))+'12'+ CAST(24+DATEPART(DAY,@DATE) AS CHAR(2)))+1 -- Special case: Dec 29-31 may belong to the next year IF ((DATEPART(mm,@DATE)=12) AND ((DATEPART(dd,@DATE)-DATEPART(dw,@DATE))>= 28)) SET @ISOweek=1 RETURN(@ISOweek) END GO
你需要ISO周.从http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=60510,这是一个实现:
drop function dbo.F_ISO_WEEK_OF_YEAR go create function dbo.F_ISO_WEEK_OF_YEAR ( @Date datetime ) returns int as /* Function F_ISO_WEEK_OF_YEAR returns the ISO 8601 week of the year for the date passed. */ begin declare @WeekOfYear int select -- Compute week of year as (days since start of year/7)+1 -- Division by 7 gives whole weeks since start of year. -- Adding 1 starts week number at 1, instead of zero. @WeekOfYear = (datediff(dd, -- Case finds start of year case when NextYrStart <= @date then NextYrStart when CurrYrStart <= @date then CurrYrStart else PriorYrStart end,@date)/7)+1 from ( select -- First day of first week of prior year PriorYrStart = dateadd(dd,(datediff(dd,-53690,dateadd(yy,-1,aa.Jan4))/7)*7,-53690), -- First day of first week of current year CurrYrStart = dateadd(dd,(datediff(dd,-53690,aa.Jan4)/7)*7,-53690), -- First day of first week of next year NextYrStart = dateadd(dd,(datediff(dd,-53690,dateadd(yy,1,aa.Jan4))/7)*7,-53690) from ( select --Find Jan 4 for the year of the input date Jan4 = dateadd(dd,3,dateadd(yy,datediff(yy,0,@date),0)) ) aa ) a return @WeekOfYear end go