查找一周中特定日期的下一次出现

时间:2018-04-18 09:49:46

标签: postgresql postgresql-9.4 dayofweek

如何将日期时间列start_at转换为星期几并找出相对于当前日期的下一个事件?

我在这里尝试将DOW添加到本周,但它看起来并不正确。

SELECT date_trunc('week', current_date) + CAST(extract(dow from start_at) || ' days' AS interval)

完整示例:

SELECT id event_id,
GENERATE_SERIES(date_trunc('week', current_date) + CAST(extract(dow from start_at) + 1 || ' days' AS interval) + start_at::time, current_date + interval '3 weeks', '1 week'::INTERVAL) AS start_at
FROM events

活动

+-----+---------------------------+---------------------+
| id  | start_at                  | recurring_schedule  |
+-----+---------------------------+---------------------+
| 358 | 2015-01-23 20:00:00 +0000 | Weekly              |
| 359 | 2016-01-22 19:30:00 +1100 | Monthly             |
| 360 | 2016-02-01 19:00:00 +1100 | Weekly              |
| 361 | 2016-02-01 20:00:00 +0000 | Weekly              |
| 362 | 2014-02-13 20:00:00 +0000 | Bi-Weekly           |
+-----+---------------------------+---------------------+

输出

+----------+---------------------------+
| event_id | start_at                  |
+----------+---------------------------+
| 35       | 2018-04-11 19:30:00 +0000 |
| 94       | 2018-04-12 20:00:00 +0100 |
| 269      | 2018-04-13 18:30:00 +0100 |
| 45       | 2018-04-13 20:00:00 +0100 |
| 242      | 2018-04-13 19:30:00 +1100 |    
| 35       | 2018-04-18 19:30:00 +0000 |
| 94       | 2018-04-19 20:00:00 +0100 |
| 269      | 2018-04-20 18:30:00 +0100 |
| 45       | 2018-04-20 20:00:00 +0100 |
| 242      | 2018-04-20 19:30:00 +1100 |
+----------+---------------------------+

1 个答案:

答案 0 :(得分:1)

尝试一下:

SELECT id event_id,    
GENERATE_SERIES(date_trunc('week', current_date)::date 
+ (extract(isodow from start_at)::int - 1) + start_at::time, current_date 
+ interval '3 weeks', '1 week'::INTERVAL) AS start_at
FROM events