从 Postgres 的日期范围中获取星期几

Get days of the week from a date range in Postgres

所以我有以下 table :

id     end_date      name      number_of_days    start_date
1   "2022-01-01"    holiday1        1            "2022-01-01"
2   "2022-03-20"    holiday2        1            "2022-03-20"
3   "2022-04-09"    holiday3        1            "2022-04-09"
4   "2022-05-01"    holiday4        1            "2022-05-01"
5   "2022-05-04"    holiday5        3            "2022-05-02"
6   "2022-07-12"    holiday6        9            "2022-07-20"

我想检查一周是否在假期范围内。

到目前为止,我可以 select 与我选择的周(week_start_date、week_end_date)重叠的假期,但我无法获得重叠发生的确切日期。

这是我正在使用的查询,我想添加一种机制来检测一周中哪几天发生重叠

SELECT * FROM holidays
where daterange(CAST(start_date AS date), CAST(end_date as date), '[]') && daterange('2022-07-18', '2022-07-26','[]')

当前查询RETURNS重叠假期,(id = 6),但是我正在尝试获取重叠发生的确切星期几(在这种情况下,应该是星期一,星期二,星期三)

您可以将 * 运算符与 tsranges 一起使用,生成一系列具有下限和上限日期的日期,最后使用 to_char 打印星期几,例如

SELECT 
  id, name, start_date, end_date, array_agg(dow) AS days
FROM (
  SELECT *,  
    trim(
      to_char(
        generate_series(lower(overlap), upper(overlap),'1 day'),
      'Day')) AS dow
  FROM holidays
  CROSS JOIN LATERAL (SELECT tsrange(start_date,end_date) * 
                             tsrange('2022-07-18', '2022-07-26')) t (overlap)
  WHERE tsrange(start_date,end_date) && tsrange('2022-07-18', '2022-07-26')) j
GROUP BY id,name,start_date,end_date,number_of_days;

 id |   name   | start_date |  end_date  |            days            
----+----------+------------+------------+----------------------------
  6 | holiday6 | 2022-07-12 | 2022-07-20 | {Monday,Tuesday,Wednesday}
(1 row)

演示:db<>fiddle