首页 > 解决方案 > 如何使用 date_part 选项在 postgres 中获取不同的日期

问题描述

如何在 PostgreSQL 中获取日期时差

我正在使用以下语法

select id, A_column,B_column, 
      (SELECT count(*) AS count_days_no_weekend 
       FROM generate_series(B_column ::timestamp , A_column ::timestamp, interval  '1 day') the_day 
       WHERE  extract('ISODOW' FROM the_day) < 5) * 24 + DATE_PART('hour', B_column::timestamp-A_column ::timestamp ) as hrs 
FROM table req where id='123'; 

如果 A_column=2020-05-20 00:00:00 和 B_column=2020-05-15 00:00:00 我想得到 72(以小时为单位)。

是否有可能在第一个中跳过周末(周六和周日),这意味着得到结果为 72 小时(不包括周末时间)

我得到 0

但我需要得到 72 小时

如果如果 A_column=2020-08-15 12:00:00 和 B_column=2020-08-15 00:00:00 我想得到 12(以小时为单位)。

标签: sqlpostgresqldatetimerecursive-querypostgresql-9.5

解决方案


我会通过计算周末时间来让数据库处理夏令时来解决这个问题。然后,我将从两个日期值之间的差异中减去中间的周末时间。


with weekend_days as (
  select *, date_part('isodow', ddate) as dow
    from table1
         cross join lateral 
           generate_series(
             date_trunc('day', b_column),
             date_trunc('day', a_column),
             interval '1 day') as gs(ddate)
   where date_part('isodow', ddate) in (6, 7)
), weekend_time as (
  select id, 
         sum( 
           least(ddate + interval '1 day', a_column) -
           greatest(ddate, b_column)
         ) as we_ival
    from weekend_days
   group by id
)
select t.id, 
       a_column - b_column as raw_difference,
       coalesce(we_ival, interval '0') as adjustment,
       a_column - b_column - 
         coalesce(we_ival, interval '0') as adj_difference
  from weekend_time w
       left join table1 t on t.id = w.id;

工作小提琴。


推荐阅读