构buildMSSQL中的年份和星期数
如果我有一个YEAR
和一个WEEK
数字,那么从这个数据构build一个DATE
的干净方法是什么? 如果星期几可能是星期一,我更喜欢它。
使用DATEADD
SqlFiddleDemo
DECLARE @y INT = 2015, @w INT = 37; SELECT [StartOfWeek] = DATEADD(wk, DATEDIFF(wk, 7, CAST(@y AS NVARCHAR(100))) + (@w-1), 7);
注意阅读关于DATEFIRST
评论。 这取决于你的文化…
根据我对你的问题的评论,这是一个从1900-01-01开始直到2173年的某个地方引入这样一个运行数字表的方法。
CREATE TABLE dbo.RunningNumbers(Number INT NOT NULL,CalendarDate DATE NOT NULL, CalendarYear INT NOT NULL,CalendarMonth INT NOT NULL,CalendarDay INT NOT NULL, CalendarWeek INT NOT NULL, CalendarYearDay INT NOT NULL, CalendarWeekDay INT NOT NULL); DECLARE @CountEntries INT = 100000; DECLARE @StartNumber INT = 0; WITH E1(N) AS(SELECT 1 FROM(VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))t(N)), --10 ^ 1 E2(N) AS(SELECT 1 FROM E1 a CROSS JOIN E1 b), -- 10 ^ 2 = 100 rows E4(N) AS(SELECT 1 FROM E2 a CROSS JOIN E2 b), -- 10 ^ 4 = 10,000 rows E8(N) AS(SELECT 1 FROM E4 a CROSS JOIN E4 b), -- 10 ^ 8 = 10,000,000 rows CteTally AS ( SELECT TOP(ISNULL(@CountEntries,1000000)) ROW_NUMBER() OVER(ORDER BY(SELECT NULL)) -1 + ISNULL(@StartNumber,0) As Nmbr FROM E8 ) INSERT INTO dbo.RunningNumbers SELECT CteTally.Nmbr,CalendarDate.d,CalendarExt.* FROM CteTally CROSS APPLY ( SELECT DATEADD(DAY,CteTally.Nmbr,{ts'1900-01-01 00:00:00'}) ) AS CalendarDate(d) CROSS APPLY ( SELECT YEAR(CalendarDate.d) AS CalendarYear ,MONTH(CalendarDate.d) AS CalendarMonth ,DAY(CalendarDate.d) AS CalendarDay ,DATEPART(WEEK,CalendarDate.d) AS CalendarWeek ,DATEPART(DAYOFYEAR,CalendarDate.d) AS CalendarYearDay ,DATEPART(WEEKDAY,CalendarDate.d) AS CalendarWeekDay ) AS CalendarExt;
这会给你带来当前的星期一:
SELECT * FROM dbo.RunningNumbers WHERE CalendarYear = 2015 AND CalendarWeek = 37 AND CalendarWeekDay=1