Función DATE_TRUNC() de PostgreSQL

Shihab Sikder 20 junio 2023
  1. el Uso de la Función DATE_TRUNC() en PostgreSQL
  2. "milisegundo" Precisión en Postgres DATE_TRUNC()
  3. Precisión "segundo" en Postgres DATE_TRUNC()
  4. "minuto" Precisión en Postgres DATE_TRUNC()
  5. "hora" Precisión en Postgres DATE_TRUNC()
  6. "día" Precisión en Postgres DATE_TRUNC()
  7. Usar DATE_TRUNC() con Query en Postgres
Función DATE_TRUNC() de PostgreSQL

Este artículo discutirá la función DATE_TRUNC() de Postgres con fragmentos de código.

el Uso de la Función DATE_TRUNC() en PostgreSQL

Es posible en Postgres truncar o redondear una marca de tiempo dada a un cierto nivel de precisión. Digamos que puede truncarlo al minuto, hora, día, mes, etc. más cercano.

En Postgres, DATE_TRUNC() tiene los siguientes intervalos.

Century
Day
Decade
Hour
Minute
Microsecond
Millisecond
Second
Month
Quarter
Week
Year

Aquí está la marca de tiempo actual. Lo usaremos en diferentes intervalos para ver el resultado.

postgres=# SELECT NOW();
              now
-------------------------------
 2022-04-29 17:30:48.256668+06
(1 row)

"milisegundo" Precisión en Postgres DATE_TRUNC()

Usaremos “milisegundo” como precisión en el DATE_TRUNC().

postgres=# SELECT DATE_TRUNC('millisecond', TIMESTAMP '2022-04-29 17:30:48.256668');
       date_trunc
-------------------------
 2022-04-29 17:30:48.256
(1 row)

El milisegundo fue 256668. Luego se truncó a 256.

Precisión "segundo" en Postgres DATE_TRUNC()

Aquí, usamos "segundo" como precisión en DATE_TRUNC().

postgres=# SELECT DATE_TRUNC('second', TIMESTAMP '2022-04-29 17:30:48.256668');
     date_trunc
---------------------
 2022-04-29 17:30:48
(1 row)

Puede ver que la parte decimal se recorta para redondear el valor.

"minuto" Precisión en Postgres DATE_TRUNC()

Usamos el “minuto” como precisión en el DATE_TRUNC().

postgres=# SELECT DATE_TRUNC('minute', TIMESTAMP '2022-04-29 17:30:48.256668');
     date_trunc
---------------------
 2022-04-29 17:30:00
(1 row)

El minuto era 30:48. Usando DATE_TRUNC(),, se convirtió en 30:00.

"hora" Precisión en Postgres DATE_TRUNC()

Usemos "hora" como precisión en DATE_TRUNC().

postgres=# SELECT DATE_TRUNC('hour', TIMESTAMP '2022-04-29 17:30:48.256668');
     date_trunc
---------------------
 2022-04-29 17:00:00
(1 row)

Puedes ver la diferencia entre 17:30:48.256668 y 17:00:00.

"día" Precisión en Postgres DATE_TRUNC()

Usa el "día" como precisión en el DATE_TRUNC().

postgres=# SELECT DATE_TRUNC('day', TIMESTAMP '2022-04-29 17:30:48.256668');
     date_trunc
---------------------
 2022-04-29 00:00:00
(1 row)

Puede ver que la hora se convirtió en 00:00:00. Redondeó el día.

Usar DATE_TRUNC() con Query en Postgres

Tengamos los siguientes MOCK_DATA en el check-in del hotel.

postgres=# SELECT * from MOCK_DATA;
 id  | first_name  |  last_name   |              email               |   gender    |  check_in
-----+-------------+--------------+----------------------------------+-------------+------------
   1 | Agustin     | Bawdon       | abawdon0@umn.edu                 | Male        | 2016-05-11
   2 | Maximilian  | Ber          | mber1@artisteer.com              | Male        | 2013-03-08
   3 | Randy       | Kline        | rkline2@pcworld.com              | Bigender    | 2019-01-01
   4 | Bonnibelle  | Mazillius    | bmazillius3@is.gd                | Female      | 2011-07-06
   5 | Rolland     | Hollidge     | rhollidge4@seesaa.net            | Male        | 2009-04-30
   6 | Sandro      | Hubbert      | shubbert5@nature.com             | Male        | 2019-11-26
   7 | Collin      | La Torre     | clatorre6@google.de              | Male        | 2016-02-12
   8 | Joleen      | Jerram       | jjerram7@instagram.com           | Female      | 2015-05-23
-- More  --

Queremos contar los ingresos de cada año.

SELECT
    date_trunc('year', check_in) year_no,
    COUNT(id) Customers
FROM
    MOCK_DATA
GROUP BY
    year_no
ORDER BY
    year_no;

Producción :

        year_no         | customers
------------------------+-----------
 2008-01-01 00:00:00+06 |        17
 2009-01-01 00:00:00+06 |        20
 2010-01-01 00:00:00+06 |        15
 2011-01-01 00:00:00+06 |        20
 2012-01-01 00:00:00+06 |        19
 2013-01-01 00:00:00+06 |        18
 2014-01-01 00:00:00+06 |        13
 2015-01-01 00:00:00+06 |        24
 2016-01-01 00:00:00+06 |        18
 2017-01-01 00:00:00+06 |        13
 2018-01-01 00:00:00+06 |        23
 2019-01-01 00:00:00+06 |        17
 2020-01-01 00:00:00+06 |        16
 2021-01-01 00:00:00+06 |        12
 2022-01-01 00:00:00+06 |         5
(15 rows)

Para saber más sobre DATE_TRUNC(), aquí está la documentación oficial. Puede usar mockaroo para generar la base de datos de ejemplo.

Shihab Sikder avatar Shihab Sikder avatar

I'm Shihab Sikder, a professional Backend Developer with experience in problem-solving and content writing. Building secure, scalable, and reliable backend architecture is my motive. I'm working with two companies as a part-time backend engineer.

LinkedIn Website

Artículo relacionado - PostgreSQL Function