首页 文章

使用基于星期几PostgreSQL的不同过滤器运行查询

提问于
浏览
2

尝试使用不同的日期过滤器运行相同的视图,具体取决于我运行它的那一天 . 如果我在星期五,星期六,星期日或星期一运行查询,则应在星期二至星期四过滤日期 . 如果我在星期二,星期三,星期四运行查询,那么日期应该在星期五过滤 . 这是仅有的两种情况 . 我正在使用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

1 回答

  • 0

    使用 extract(dow from current_date) ,它给出当前星期几(星期日为0),见Date/Time Functions and Operators .

    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 更简单,可能更快 .

相关问题