WHERE CASE WHEN时间间隔

时间:2018-02-11 18:16:07

标签: sql

当客户访问时间不在(肯德基小时关闭期间)时过滤BrandCode的SQL。

SELECT * 
FROM EatTime e 
LEFT JOIN CloseHour c 
    ON DATEPART(weekday, e.VisitDate) = DATEPART(weekday, c.MonthDate) 
WHERE (
    CASE 
        WHEN DATEPART(weekday,e.VisitDate) = 1 
            THEN (e.VisitTime NOT BETWEEN '10:00:00' AND '13:00:00')
        WHEN DATEPART(weekday,e.VisitDate) = 3 
            THEN (e.VisitTime NOT BETWEEN '21:00:00' AND '22:00:00')
    END
)

以下是一些示例数据:

CustomerId BrandCode  Visit  VisitTime  VisitDate  Brand  CloseHR  MonthDate
         1 Skake          1  10:05:22   2018/2/4   KFC    10:00:00 2018/2/4
         1 Skake          1  10:05:22   2018/2/4   KFC    11:00:00 2018/2/4
         1 Skake          1  10:05:22   2018/2/4   KFC    12:00:00 2018/2/4
         1 Skake          1  10:05:22   2018/2/4   KFC    13:00:00 2018/2/4
         2 KFC            1  11:05:22   2018/2/6   KFC    21:00:00 2018/2/6
         2 KFC            1  11:05:22   2018/2/6   KFC    22:00:00 2018/2/6
         3 BurgerKing     1  12:05:22   2018/2/4   KFC    10:00:00 2018/2/4
         4 Denny          1  13:05:22   2018/2/4   KFC    10:00:00 2018/2/4

1 个答案:

答案 0 :(得分:1)

我想你在寻找这样的东西:

SELECT* 
FROM EatTime e 
LEFT JOIN CloseHour c
    ON DATEPART(weekday, e.VisitDate) = DATEPART(weekday, c.MonthDate) 
WHERE 
( 
    (
        DATEPART(weekday, e.VisitDate) = 1 
        AND e.VisitTime NOT BETWEEN '10:00:00' AND '13:00:00'
    )
    OR 
    ( 
        DATEPART(weekday, e.VisitDate) = 3
        AND e.VisitTime NOT BETWEEN '21:00:00' AND '22:00:00'
    )
)