如果我在SQL查询中有一个周数,如何获取日期值。
如果我通过26,那就应该给我06/24/2012。如果我通过27,我应该得到07/01/2012
任何帮助将不胜感激:)
SOTS
答案 0 :(得分:0)
在SQL Server中
DECLARE @StartDate DATE, @WeekVal INT
SET @WeekVal = 26 -- Set the week number
SET @StartDate = DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0) -- Start of current year
;WITH cte AS (
SELECT @StartDate AS DateVal, DATEPART(wk, @StartDate) AS WeekVal, 1 AS RowVal
UNION ALL
SELECT DATEADD(d, 1, DateVal), DATEPART(wk, DATEADD(d, 1, DateVal)), RowVal + 1
FROM cte WHERE RowVal < 365
)
SELECT MIN(DateVal) StartOfWeek
FROM cte
WHERE WeekVal = @WeekVal
OPTION (MAXRECURSION 365);
答案 1 :(得分:0)
SELECT DATEADD(week, n, '11/25/2011');
以n为周数
答案 2 :(得分:0)
如果这不起作用,请尝试使用WEEK()
代替WEEKOFYEAR()
。
CURDATE() - INTERVAL WEEKDAY(CURDATE()) DAY + INTERVAL (WEEKNO - WEEKOFYEAR(CURDATE())) WEEK
答案 3 :(得分:0)
这将为您提供一周的开始和结束日期。 [对于SQL Server]
Declare @week integer set @week = 26
Declare @Year Integer Set @Year = year(getdate())
declare @date datetime
-- ------------------------------------
Set @date = DateAdd(day, 0,
DateAdd(month, 0,
DateAdd(Year, @Year-1900, 0)))
set @date = Dateadd(week, @week-1, @date)
select @date startweek, DATEADD (D, -1 * DatePart (DW, @date) + 7, @date) endweek
这是它的结果:
startweek endweek
----------------------- -----------------------
2012-07-01 00:00:00.000 2012-07-07 00:00:00.000
(1 row(s) affected)