sql - where 子句上的星期几和时间

标签 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 完成此操作?

最佳答案

使用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;

关于sql - where 子句上的星期几和时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50777712/

相关文章:

postgresql - Postgis上传大量空间数据有什么好方法?

javascript - 对于 jQuery(不是 jQuery UI!)来说,这是一个多么好的日期+时间选择器?

mysql - 我需要的是多左外连接和冷融合吗?

sql - 如何从所有列中查询 max(len)?

postgresql - 阻止 PostgreSQL 日志文件填满磁盘

java - Postgres 中结构类型列的元数据

算法:找到最小倍数

javascript - 使用 moment.js 获取不同时区的当前时间

sql - oracle基于单列重复行

mysql - 从一个表中获取记录,其中 id 在 mysql json 中的第二个表数组中