【问题标题】:Group by week and consider Saturday as start day of the week按周分组并将星期六视为一周的开始日
【发布时间】:2020-01-28 14:54:31
【问题描述】:

我想查询我的 postgresql 数据并按周对结果进行分组,所以我使用以下查询:

select
   date_trunc ('week', date_column) as week,
   sum (orders) as orders_count
from database
group by week

但它使用星期一作为一周的开始日,而我希望我的一周像“星期六 -> 星期五”。我怎样才能做到这一点?

【问题讨论】:

    标签: sql postgresql date


    【解决方案1】:

    只需减去两天,你就会在星期六降落:

    select
       date_trunc('week', date_column)::date - 2 as week,
       sum (orders) as orders_count
    from the_table
    group by week
    

    【讨论】:

    • 但这只是改变了 x 轴的标签,并且总和值与我的查询相同。
    【解决方案2】:

    你可以只抵消两天,如下:

    select
       date_trunc ('week', date_column + interval '2 days') - interval '2 days' as week,
       sum (orders) as orders_count
    from database
    group by week
    

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 1970-01-01
      • 2017-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 2012-11-27
      相关资源
      最近更新 更多