我在MS SSMS中使用以下SQL代码来查找周结束日期。我经常需要在星期三和星期日之间切换作为结束日。旁注,我的数据集通常在100,000以上。
除了使用日历表之外,还有一种更有效的方法吗?
/* Declare Variables */
DECLARE @WeekendingDay VARCHAR(10);
DECLARE @DayNumber INT;
DECLARE @InputDate VARCHAR(10);
DECLARE @conInputDate DATETIME;
DECLARE @outWeekending DATETIME;
DECLARE @CovertToInt VARCHAR(10);
/* --------------------Inputs-------------------- */
/* uncomment the weekending day you want */
--Set @WeekendingDay = 'Monday'
--Set @WeekendingDay = 'Tuesday'
--Set @WeekendingDay = 'Wednesday'
--Set @WeekendingDay = 'Thursday'
--Set @WeekendingDay = 'Friday'
--Set @WeekendingDay = 'Saturday'
SET @WeekendingDay = 'Sunday';
/* Date you want the weekending of */
SET @InputDate = '29/12/2016';
/* --------------------Process-------------------- */
SET @DayNumber = CASE @WeekendingDay
WHEN 'Sunday' THEN 1
WHEN 'Monday' THEN 2
WHEN 'Tuesday' THEN 3
WHEN 'Wednesday' THEN 4
WHEN 'Thursday' THEN 5
WHEN 'Friday' THEN 6
WHEN 'Saturday' THEN 7
END;
SET @conInputDate = CONVERT(DATETIME, @InputDate, 103);
SET @outWeekending = DATEADD(dd,
CASE WHEN DATEPART(DW, @conInputDate) = @DayNumber
THEN 0
ELSE -1 * DATEPART(DW, @conInputDate) + 7
+ @DayNumber
END, @conInputDate);
/* --------------------Output-------------------- */
PRINT @outWeekending;
答案 0 :(得分:1)
这将给你一周的星期一。根据您想要用作最后一天的日期,您可以根据需要进行调整。
DECLARE @date DATETIME = GETUTCDATE()-5
SELECT
@date
,DATEADD(WEEK, DATEDIFF(WEEK, 0, @date),0) --Monday
,DATEADD(DD,1,DATEADD(WEEK, DATEDIFF(WEEK, 0, @date),0)) --Tuesday
,DATEADD(DD,2,DATEADD(WEEK, DATEDIFF(WEEK, 0, @date),0)) --Wednesday
,DATEADD(DD,3,DATEADD(WEEK, DATEDIFF(WEEK, 0, @date),0)) --Thursday
,DATEADD(DD,4,DATEADD(WEEK, DATEDIFF(WEEK, 0, @date),0)) --Friday
,DATEADD(DD,5,DATEADD(WEEK, DATEDIFF(WEEK, 0, @date),0)) --Saturday
,DATEADD(DD,6,DATEADD(WEEK, DATEDIFF(WEEK, 0, @date),0)) --Sunday