Postgres - 获取第 X 周的星期一

Postgres - Get the monday of week X

在 Postgres 中,给定 Y 年的第 X 周,如何获取第 week/year 的星期一日期?

示例:

monday_of(1, 2020) -> '2020-01-30'
monday_of(33, 2020) -> '2020-08-10'
monday_of(53, 2020) -> '2020-12-28'
monday_of(54, 2020) -> '' (year does not have 54 weeks)

您可以使用日期算法。假设yrwk是年周参数:

date_trunc('week', make_date(yr, 1, 1)) + (wk- 1) * interval '1 week'

但是请注意,这不会检测超出范围的周数(但您可以轻松添加条件逻辑来处理该问题)。

Demo on DB Fiddle:

select yr, wk, date_trunc('week', make_date(yr, 1, 1)) + (wk- 1) * interval '1 week' res
from (values (1, 2020), (33, 2020), (53, 2020), (54, 2020)) as t(wk, yr)
  yr | wk | res                   
---: | -: | :---------------------
2020 |  1 | 2019-12-30 00:00:00+00
2020 | 33 | 2020-08-10 00:00:00+01
2020 | 53 | 2020-12-28 00:00:00+00
2020 | 54 | 2021-01-04 00:00:00+00