PostgreSQL
 sql >> Base de données >  >> RDS >> PostgreSQL

Division datetime SQL/Postgres/normalisation

Pour obtenir les lignes nécessaires, commencez par utiliser une set return function avec une jointure latérale . À partir de là, utilisez CASE instructions et arithmétique de date pour extraire les valeurs pertinentes.

Voici un exemple pour vous aider à démarrer :

with data as (
  select id, start_date, end_date
  from (values
    (1, '2014-12-02 14:12:00+00'::timestamptz, '2014-12-03 06:45:00+00'::timestamptz),
    (2, '2014-12-05 15:25:00+00'::timestamptz, '2014-12-05 07:29:00+00'::timestamptz)
  ) as rows (id, start_date, end_date)
)
select data.id,
      case days.d = date_trunc('day', data.start_date)
        when true then data.start_date
        else days.d
      end as start_date,
      case days.d = date_trunc('day', data.end_date)
        when true then data.end_date
        else days.d + interval '1 day' - interval '1 sec'
      end as end_date
from data
join generate_series(
      date_trunc('day', data.start_date),
      date_trunc('day', data.end_date),
      '1 day'
      ) as days (d)
      on days.d >= date_trunc('day', data.start_date)
      and days.d <= date_trunc('day', data.end_date)

 id |       start_date       |        end_date        
----+------------------------+------------------------
  1 | 2014-12-02 15:12:00+01 | 2014-12-02 23:59:59+01
  1 | 2014-12-03 00:00:00+01 | 2014-12-03 07:45:00+01
  2 | 2014-12-05 16:25:00+01 | 2014-12-05 08:29:00+01
(3 rows)

En passant, selon ce que vous faites, il peut être plus judicieux pour vous d'utiliser un plage de dates :

with data as (
  select id, start_date, end_date
  from (values
    (1, '2014-12-02 14:12:00+00'::timestamptz, '2014-12-03 06:45:00+00'::timestamptz),
    (2, '2014-12-05 07:25:00+00'::timestamptz, '2014-12-05 15:29:00+00'::timestamptz)
  ) as rows (id, start_date, end_date)
)
select data.id,
      tstzrange(data.start_date, data.end_date)
from data;

 id |                      tstzrange                      
----+-----------------------------------------------------
  1 | ["2014-12-02 15:12:00+01","2014-12-03 07:45:00+01")
  2 | ["2014-12-05 08:25:00+01","2014-12-05 16:29:00+01")
(2 rows)