我希望获得过去3个工作日内发生的任何数据 如果今天是星期一,我希望我的查询提取上周三,周四和周五发生的数据 如果是星期二,请提取周四,周五和周一发生的数据。 如果是星期三,请在周五,周一,周二拉。等
这是我在WHERE语句中到目前为止所做的,但我知道这是不正确的。
AND CASE
WHEN DATENAME(DW, GETDATE()) = 'Monday' THEN CAST(PE.SchedDt AS DATE) BETWEEN DATEADD(DAY,-5,CAST(GETDATE()AS DATE)) AND DATEADD(DAY,-3,CAST(GETDATE()AS DATE))
WHEN DATENAME(DW, GETDATE()) = 'Tuesday' THEN CAST(PE.SchedDt AS DATE) BETWEEN DATEADD(DAY,-5,CAST(GETDATE()AS DATE)) AND DATEADD(DAY,-1,CAST(GETDATE()AS DATE))
WHEN DATENAME(DW, GETDATE()) = 'Wednesday' THEN CAST(PE.SchedDt AS DATE) BETWEEN DATEADD(DAY,-5,CAST(GETDATE()AS DATE)) AND DATEADD(DAY,-2,CAST(GETDATE()AS DATE))
ELSE CAST(PE.SchedDt AS DATE) BETWEEN DATEADD(DAY,-3,CAST(GETDATE()AS DATE)) AND DATEADD(DAY,-1,CAST(GETDATE()AS DATE))
END
非常感谢任何帮助!
答案 0 :(得分:1)
您可以使用WEEKDAY()函数将工作日分配给每个日期。然后你必须比较你当前的工作日WEEKDAY(CURDATE())是否在3的范围内。
CREATE TABLE data_table (date_column DATE, some_data VARCHAR(1));
INSERT INTO data_table
VALUES ('2018-02-12', 'b'),('2018-02-14', 'a'),('2018-02-13', 'c'),
('2018-02-15', 'b'),('2018-02-16', 'a'),('2018-02-15', 'd'),
('2018-02-11', 'a'),('2018-02-10', 'e');
SELECT *
FROM (
SELECT a.*,WEEKDAY(date_column) weekday, WEEKDAY(CURDATE()) current_day
FROM data_table a
) b
WHERE
(b.weekday in (2,3,4) and current_day = 0)
or (b.weekday in (3,4,0) and current_day = 1)
or (b.weekday in (4,0,1) and current_day = 2)
or (b.weekday < current_day && b.weekday >= current_day - 3);