PostgreSQL:如何在 sql 查询中将 date_trunc 周开始日从星期一更改为另一天?

Sey*_*ini 6 sql postgresql weekday

我想date_trunc在日期时间列上使用PostgreSQL 中的函数来聚合一周内的数据。

例如,我需要每周获得销售数量。

问题是date_trunc('week', datetime_column)函数将星期一视为一周的开始日,而我的一些客户在日历中使用不同的开始日(如星期六)。

我试过

 SELECT date_trunc('WEEK',(time_id + interval '2 day'))- interval '2 day' AS WEEK
Run Code Online (Sandbox Code Playgroud)

但它很乱,我认为必须有更好的方法。

Y.K*_*.K. 1

试试这个

select
    datetime_column
    - extract(isodow from datetime_column) + 3  -- 3 is the weekday number to which we want to truncate
    - cast(extract(isodow from datetime_column) < 3 as int) * 7  -- 3 is the weekday number to which we want to truncate
from
    <table_name>
Run Code Online (Sandbox Code Playgroud)