【发布时间】:2020-10-26 04:14:01
【问题描述】:
希望有人可以在这里提供一些建议,我正在使用 PostgreSQL 数据库。
此查询的目的是确定当前允许访问的用户。目标是提供日期和时间范围作为输入,并查看在指定日期和时间范围内可以被允许访问的用户帐户。
表格是这样设置的,“开始时间”和“结束时间”的时间列指定了允许用户的时间范围。然后是一周中每一天的布尔列,指定是否允许该用户在当天的时间范围内访问。
[START TIME] [END TIME] [MON] [TUES] [WED] [THURS] [FRI] [SAT] [SUN]
09:00:00 11:00:00 True True True True True False False
现在,这看起来很简单,但在我看来,系统需要首先知道星期几,然后使用一个冗长的“case when”来表示“如果输入的日期是星期一和 table.mon = 此用户为 true,则此用户符合条件。
到目前为止,我有这样的事情:
DO $$
DECLARE
--Specify 'variables'
active_date timestamp := '2020-10-4';
start_time time := '00:00:00';
end_time time := '23:59:00';
day_of_week text := to_char(active_date, 'day');
BEGIN
CREATE TEMP TABLE temp_output ON COMMIT DROP AS
select distinct
date(account.lastupdated) as "Date",
concat(to_char(account.start_time, 'HH:MI'), ' - ', to_char(account.end_time, 'HH:MI')) as "Time Range"
from account
where account.lastupdated >= active_date AND account.lastupdated < active_date + interval '1 day'
and account.start_time >= start_time AND account.end_time <= end_time;
END $$;
SELECT * FROM temp_output;
我坚持的是,如果输入的日期对于返回的每一行都有一个布尔值“真”,那么输出应该只显示值。
类似:
case when day_of_week = 'sunday' and account.sun = "True" then ...
when day_of_week = 'monday' and account.mon = "True" then...
when day_of_week = 'tuesday' and account.tues = "True" then...
但是如何根据输入的日期为整个结果集实现这个逻辑呢?
【问题讨论】:
-
也许处理这个问题的最好方法是在底部加上一个很长的 where 子句?其中 (day_of_week = 'sunday' and account.sun = True) 或 (day_of_week = 'monday' and account.mon = True) 或...
标签: sql postgresql