如果我有一个YEAR
和一个WEEK
号码,那么从这个构建DATE
的方法是什么?如果星期几可能是星期一,我更喜欢它。
答案 0 :(得分:4)
使用DATEADD
<强> Rextester Demo 强>
DECLARE @y INT = 2015,
@w INT = 37;
SELECT
[StartOfWeek] = DATEADD(wk,DATEDIFF(wk,7,CAST(@y AS NVARCHAR(100))) + (@w-1),7);
答案 1 :(得分:2)
注意阅读有关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
答案 2 :(得分:0)
我使用以下查询解决了该问题:
dateadd(week, the_week_column-1, to_date(cast(the_year_column as string), 'YYYY'))
其中
to_date(cast(the_year_column as string), 'YYYY')
返回年份的开始日期,例如2018-01-01 the_week_column - 1
指定应在开始日期前增加几周。