【问题标题】:How many seconds passed by grouped by hour between two dates两个日期之间按小时分组的秒数
【发布时间】:2016-06-27 14:54:31
【问题描述】:

假设我有一个开始日期2016-06-19 09:30:00 和一个结束日期2016-06-19 10:20:00

我想在开始下一小时之前或到达按小时和日期分组的以秒为单位的最后时间之前每小时经过的时间,我试图达到的结果(没有任何成功)将是像这样:

hour |    date    | time_elapsed_in_seconds
 9   | 2016-06-19 |  1800 (there are 1800 seconds between 09:30:00 and 10:00:00)
 10  | 2016-06-19 |  1200 (there are 1200 seconds between 10:00:00 and 10:20:00)

【问题讨论】:

  • 你能给我们一些样本数据吗?很难想象我们应该查询什么。
  • @TimBiegeleisen 数据是开始日期和结束日期,我在表格中有一个 start_date 和一个 end_date 以及另一个信息(这是不相关的)

标签: postgresql date-arithmetic seconds


【解决方案1】:

试试这个:

        with table1 as (
      select '2016-06-19 09:30:00'::timestamp without time zone start_date,'2016-06-19 10:20:00'::timestamp without time zone end_date
      )


    select extract(hour from the_hour) "hour",the_hour::date "date",extract (epoch from (new_end-new_start)) "time_elapsed" from (
        select the_hour,CASE WHEN date_trunc('hour',start_date)=the_hour then start_date else the_hour end new_start,
                    CASE WHEN date_trunc('hour',end_date)=the_hour then end_date else the_hour+'1 hour'::interval end new_end 
           from (
              select generate_series(date_trunc('hour',start_date),end_date,'1 hour'::interval) the_hour,start_date,end_date from table1 
            ) a 
         ) b

【讨论】:

    猜你喜欢
    • 2012-05-19
    • 1970-01-01
    • 2012-12-03
    • 2016-11-07
    • 1970-01-01
    • 2021-02-13
    • 1970-01-01
    • 2015-06-28
    • 2011-07-29
    相关资源
    最近更新 更多