【问题标题】:I would like to add a column to my table showing the week number in the data, based on the data time on Postgresql我想根据 Postgresql 上的数据时间在我的表中添加一列,显示数据中的周数
【发布时间】:2019-12-26 20:29:51
【问题描述】:

我在 Postgresql 的表中有一个日期字段。我想添加另一列显示每个日期的周数。但是周数应该基于数据的时间间隔。我的意思是,如果数据从“2018-05-02”开始,则 Week1 应该涵盖“2018-05-02”和“2018-05-08”之间的日子。

date_trunc 函数不适用于这种情况。

【问题讨论】:

  • “Week1”是什么意思?第一周是第一次约会的那一周吗?什么时候开始计数?
  • 西欧周数?还是美国? (大不同)

标签: postgresql date customization week-number


【解决方案1】:

您应该能够通过减去最短日期并提取天数来计算:

create table test (a timestamp);
insert into test values ('2019-01-01T00:00:00');
insert into test values ('2019-02-01T00:00:00');

select a, floor(extract(days from (a - (select min(a) from test)))/7) as week
FROM test;
          a          | week
---------------------+------
 2019-01-01 00:00:00 |    0
 2019-02-01 00:00:00 |    4

insert into test values ('2018-01-01T00:00:00');
select a, floor(extract(days from (a - (select min(a) from test)))/7) as week
FROM test;
          a          | week
---------------------+------
 2019-01-01 00:00:00 |   52
 2019-02-01 00:00:00 |   56
 2018-01-01 00:00:00 |    0
(3 rows)

【讨论】:

    猜你喜欢
    • 2019-12-27
    • 1970-01-01
    • 2018-07-22
    • 1970-01-01
    • 2021-03-24
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    相关资源
    最近更新 更多