将周名称转换为日期SQL

时间:2017-12-07 19:47:26

标签: sql-server sql-server-2008 date

我正在尝试根据我的查询将周数转换为实际日期:

示例:week 1 2017应转换为January 2, 2017

SELECT CONVERT(nvarchar(10),DATEADD(day,DATEPART(WEEK,[DeliveryDate])*7-(DATEPART(WEEKDAY,CAST(DATEPART(YEAR,[DeliveryDate]) as nvarchar(4))+'-01-01')-2),CAST(DATEPART(YEAR,[DeliveryDate]) as nvarchar(4))+'-01-01'),126) AS week_name,
AVG(DATEDIFF(day, CONVERT(date, [UnloadDate]), CONVERT(date, [DeliveryDate]))) as Average_Delivery_Days FROM [CARGODB].[dbo].[Cargo_Transactions] 
WHERE [DeliveryDate] IS NOT NULL AND [DeliveryDate] != 0 
AND [UnloadDate] IS NOT NULL AND [UnloadDate] != 0 AND [DeliveryDate] > [UnloadDate] 
AND [Deleted] = 0 and [StageID] = 'D' AND [RouteID] IS NOT NULL AND [RouteID] != '' AND CONVERT(date, [DeliveryDate]) BETWEEN '2016-01-01' AND GETDATE()
AND CONVERT(date, [DeliveryDate]) >= DATEADD(week, -24, getdate()) GROUP BY DATEPART(YEAR,[DeliveryDate]), DATEPART(WEEK,[DeliveryDate]) ORDER BY DATEPART(YEAR,[DeliveryDate]) ASC, DATEPART(WEEK,[DeliveryDate]) ASC;

这部分:

CONVERT(nvarchar(10),DATEADD(day,DATEPART(WEEK,[DeliveryDate])*7-(DATEPART(WEEKDAY,CAST(DATEPART(YEAR,[DeliveryDate]) as nvarchar(4))+'-01-01')-2),CAST(DATEPART(YEAR,[DeliveryDate]) as nvarchar(4))+'-01-01'),126)

来自link

但我检查了我的数据,我认为这不正确。我比较了一个Epoch Converter。例如:week 25 2017应为June 19, 2017,但它显示June 26, 2017,当我在Epoch转换器中检查日期时,它应为week 26 2017,依此类推。

更新

我找到了一种方法来获得我想要的部分:

CONVERT(varchar(10),dateadd (week, DATEPART(WEEK, [DeliveryDate]), dateadd (year, DATEPART(YEAR, [DeliveryDate])-1900, 0)) - 4 - datepart(dw, dateadd (week, DATEPART(WEEK, [DeliveryDate]), dateadd (year, DATEPART(YEAR, [DeliveryDate])-1900, 0)) - 4) + 1, 126)

它给了我周日作为星期日,但我希望星期一星期一开始,所以我添加了SET DATEFIRST 1。但在将其添加到我的查询后,它会转发到下一个星期一。我希望它是:June 18, 2017 (Sunday)进入June 19, 2017 (Monday),但我得到了June 26, 2017 (Monday)

我的查询有什么问题?

1 个答案:

答案 0 :(得分:0)

这只是我理解的例子。 您可以提供各种样本数据并解释您的外出。

    declare @i varchar(50)='week 1 2017'

      select weekNumber,FOY,dateadd(day,-6,dateadd(week,cast(weekNumber as int),cast(FOY as datetime)))ReqDate
 from
 (
select substring(ltrim(replace(@i,'week','')),0,CHARINDEX(' ',ltrim(replace(@i,'week','')))) weekNumber,
right(@i,4) +'-01-01'FOY

)t4