PostgreSQL - 跨年获得一致的年周对

PostgreSQL - Getting consistent year week pairs across years

我一直在努力寻找在 Postrge 中检索一致(年、周)对的解决方案SQL。

看完问题, and, in particular, at

Grouping by date_part('year', x), date_part('week', x) is most likely not what the user wants and should be considered incorrect. For example the first day of 2017 is still part of week 52 that started in 2016 and therefore the (2017, 52) pair is probably not at all what you want as it sorts to the end of 2017. Using ´date_trunc('week', x)` on the other hand works as one would expect.

我尝试了 date_truncdate_part 的一些组合。但是,none 似乎给出了一致的结果。

例如:考虑这两个不同年份的日期:'2017-01-01''2020-01-01'

我认为对他们来说正确的(年、周)对应该是 (2016, 52)(2020, 1)

我不知道如何写一个 SQL 语句来给出这两个结果。

我试过了:

1.

SELECT date_part('year', date_trunc('week', TIMESTAMP '2017-01-01 00:00:00')); --2016 OK
SELECT date_part('week', date_trunc('week', TIMESTAMP '2017-01-01 00:00:00')); --52 OK
SELECT date_part('year', date_trunc('week', TIMESTAMP '2020-01-01 00:00:00')); --2019 BUT I NEED 2020
SELECT date_part('week', date_trunc('week', TIMESTAMP '2020-01-01 00:00:00')); --1 OK
SELECT date_part('year', TIMESTAMP '2017-01-01 00:00:00'); --2017 BUT I NEED 2016
SELECT date_part('week', TIMESTAMP '2017-01-01 00:00:00'); --52 OK
SELECT date_part('year', TIMESTAMP '2020-01-01 00:00:00'); --2020 OK
SELECT date_part('week', TIMESTAMP '2020-01-01 00:00:00'); --1 OK

不管怎样,总会有问题的,我可能会想要一些能给出正确结果的东西。我的问题是,当我按年和周分组时,这样有时我会考虑超过 7 天,我需要避免这种情况。

week 单位 returns 基于 ISO 标准的周数。要获得等效年份,请使用 isoyear

SELECT date_part('isoyear', TIMESTAMP '2017-01-01 00:00:00'), 
       date_part('week', TIMESTAMP '2017-01-01 00:00:00'),
       date_part('isoyear', TIMESTAMP '2020-01-01 00:00:00'), 
       date_part('week', TIMESTAMP '2020-01-01 00:00:00'); 

returns:

date_part | date_part | date_part | date_part
----------+-----------+-----------+----------
     2016 |        52 |      2020 |         1