我正在尝试将数据中的datetimerange列拆分为一周的开始 - 结尾。我得到它使用此查询,但问题是我的数据中的日期不是一周的开始,我想从我的数据而不是startData
的日期但是当我添加了ActualStartDate选项时,这给了我同一周的多天行数,这不是我想要的。
我的数据中包含这些日期。
11/12/2014
11/13/2014
11/14/2014
11/15/2014
11/18/2014
11/21/2014
11/22/2014
我的查询:
SELECT DISTINCT
DATEPART(ww, Convert(varchar, [initiateDateTime] ,101)) AS Week,
CONVERT(varchar, [initiateDateTime],101) as ActualStartDate,
--CONVERT(varchar, DATEADD(dd, -(DATEPART(dw, Convert(varchar, [initiateDateTime],101))-1), Convert(varchar, [initiateDateTime],101)),101) AS StartDateWeek,
CONVERT(varchar, DATEADD(dd, 6-(DATEPART(dw, Convert(varchar, [initiateDateTime],101))-1), Convert(varchar, [initiateDateTime],101)),101) AS EndDateWeek
FROM [LogData].[dbo].[InitLogs]
WHERE [initiateDateTime] BETWEEN '11/12/2014' AND '01/08/2015'
GROUP BY DATEPART(ww, Convert(varchar, [initiateDateTime] ,101)),CONVERT(varchar, [initiateDateTime],101)
ORDER BY DATEPART(ww, Convert(varchar, [initiateDateTime] ,101))
输出:
46 11/12/2014 11/15/2014
46 11/13/2014 11/15/2014
46 11/14/2014 11/15/2014
46 11/15/2014 11/15/2014
47 11/18/2014 11/22/2014
47 11/21/2014 11/22/2014
47 11/22/2014 11/22/2014
但是,AS 11/13和11/14与46在同一周,我希望查询只返回一行
46 11/12/2014 11/15/2014
47 11/18/2014 11/22/2014
感谢您的光临。
更新: 解决它与嵌套的SQL这样的实际日期
(SELECT
Top 1 (Convert(varchar, [initiateDateTime] ,101))
FROM [LogData].[dbo].[InitLogs]
WHERE
[initiateDateTime] BETWEEN '11/1/2014' AND '01/08/2015'
AND
DATEPART(wk, Convert(varchar, [initiateDateTime] ,101)) = DATEPART(wk, Convert(varchar, FL.initiateDateTime,101))
) As StartDate,