最近在做周报填报的功能,其中需要算一下周次及起始日期。本打算用程序代码算一下的,但是感觉用sql更有意思,所以搜了一些相关的知识以及前人写的相关的sql语句,在此基础上进行了完善。
1、国际标准周日是每周的第一天,但是在咱们中国人还是习惯周一为每周的第一天,因此首先要把周一设置为每周的第一天
SET DATEFIRST 1
2、计算你传过来时间段的开始日期是本年的第几周和周几(如果为周日则周次再加一)
DATEPART(dw, @tmpDate)
SELECT DATEPART(WEEK, @tmpDate)
3、完整sql(这里我传的时间段是2017-01-15至2017-01-31)
SET DATEFIRST 1
DECLARE @tmpDate DATETIME
DECLARE @index INT
DECLARE @table TABLE
(
WeekTimes INT ,
FirstDay DATE ,
EndDay DATE
)
SET @tmpDate = '2017-1-15'
DECLARE @YearFistWK INT= DATEPART(dw, @tmpDate)
SET @index = ( SELECT DATEPART(WEEK, @tmpDate)
)
IF ( @YearFistWK = 7 )
BEGIN
SET @index = @index + 1
END
WHILE @tmpDate <= '2017-1-31'
BEGIN
INSERT INTO @table
SELECT @index ,
a.FirstDay ,
b.EndDay
FROM ( SELECT 1 AS ID ,
DATEADD(wk, DATEDIFF(wk, 0, @tmpDate), 0) AS FirstDAy
) a
LEFT JOIN ( SELECT 1 AS ID ,
DATEADD(wk,
DATEDIFF(wk, 0, @tmpDate),
6) AS EndDay
) b ON a.ID = b.ID
SET @tmpDate = DATEADD(DAY, 7, @tmpDate)
SET @index = @index + 1
END
SELECT *
FROM @table
4、运行结果