星期几和where子句的时间

时间:2018-06-09 19:20:56

标签: sql postgresql time

我有以下SQL查询可以正常工作。根据行的时区,它在一个时间范围内得到行

SELECT *, (now() AT TIME ZONE account.timezone)::time AS local_time 
FROM contact INNER JOIN account ON account.id = contact.account_id 
WHERE (now() AT TIME ZONE account.timezone)::time BETWEEN '17:30'::time AND '22:00'::time

但是如果是周末或工作日,我希望有不同的时间。在周末,我想要15:30而不是17:30

如何使用Postgresql完成这项工作?

2 个答案:

答案 0 :(得分:1)

使用EXTRACT(DOW FROM ...)获取星期几。然后在周六或周日使用CASE ... END重新调整15:30,否则使用17:30。

SELECT *,
       (now() AT TIME ZONE account.timezone)::time AS local_time 
       FROM contact
            INNER JOIN account
                       ON account.id = contact.account_id 
       WHERE (now() AT TIME ZONE account.timezone)::time BETWEEN CASE
                                                                   WHEN EXTRACT(DOW FROM now() AT TIME ZONE account.timezone) IN (6, 0)
                                                                     THEN '15:30'::time
                                                                   ELSE
                                                                     '17:30'::time
                                                                 END
                                                                 AND '22:00'::time;

答案 1 :(得分:1)

我会用简单的布尔逻辑来做到这一点:

SELECT *, (now() AT TIME ZONE a.timezone)::time AS local_time 
FROM contact c INNER JOIN
     account a
     ON a.id = c.account_id 
WHERE (EXTRACT(DOW FROM now() AT TIME ZONE a.timezone) IN (6, 0) AND
       (now() AT TIME ZONE a.timezone)::time BETWEEN '15:30'::time AND '22:00'::time
      ) OR
      (EXTRACT(DOW FROM now() AT TIME ZONE a.timezone) NOT IN (6, 0) AND
       (now() AT TIME ZONE a.timezone)::time BETWEEN '17:30'::time AND '22:00'::time
      );

由于重复,我可能倾向于将其称为:

SELECT *, nowtz::time AS local_time 
FROM (VALUES (now() AT TIME ZONE a.timezone)) v(nowtz) CROSS JOIN
     contact c INNER JOIN
     account a
     ON a.id = c.account_id 
WHERE (EXTRACT(DOW FROM nowtz) IN (6, 0) AND
       (nowtz::time BETWEEN '15:30'::time AND '22:00'::time)
      ) OR
      (EXTRACT(DOW FROM nowtz) NOT IN (6, 0) AND
       (nowtz::time BETWEEN '17:30'::time AND '22:00'::time)
      )

WHERE逻辑可以简化为:

WHERE (EXTRACT(DOW FROM nowtz) IN (6, 0) AND nowtz::time >= '15:30'::time OR
       nowtz::time >= '17:30'::time 
      ) AND
      nowtz::time <= '22:00'::time