根据PostgreSQL的工作日使用不同的过滤器运行查询



根据运行日期,尝试使用不同的日期筛选器运行同一视图。如果我在周五、周六、周日或周一运行查询,则日期应在周二至周四进行筛选。如果我在周二、周三、周四运行查询,那么应该在周五至周一过滤日期。这是仅有的两种情况。我使用的是PostgreSQL。

除此之外,视图本身非常简单:

select * from tbl_1
where date between ____ and _____

我确实有一个可以加入的日期表。我试过这样的东西:

(select date
,case when day_of_week_iso IN(2, 3, 4) THEN 1 ElSE 4 END as "day"
from tbl.date
where date = current_date
) dates

使用extract(dow from current_date),它给出一周中的当前日期(星期日为0),请参阅日期/时间函数和运算符。

select *
from tbl_1
where case extract(dow from current_date)
    when 2 then date between current_date- 4 and current_date- 1
    when 3 then date between current_date- 5 and current_date- 2
    when 4 then date between current_date- 6 and current_date- 3
    when 5 then date between current_date- 3 and current_date- 1
    when 6 then date between current_date- 4 and current_date- 2
    when 0 then date between current_date- 5 and current_date- 3
    when 1 then date between current_date- 6 and current_date- 4
    end;

您可以使用自己的函数来缩短代码,但在所有情况下使用case更简单,可能更快。

最新更新