¿Cómo seleccionar id con fecha máxima grupo por categoría en PostgreSQL?


Por ejemplo, me gustaría seleccionar id con fecha máxima grupo por categoría, el resultado es: 7, 2, 6

id  category  date
1   a         2013-01-01
2   b         2013-01-03
3   c         2013-01-02
4   a         2013-01-02
5   b         2013-01-02
6   c         2013-01-03
7   a         2013-01-03
8   b         2013-01-01
9   c         2013-01-01

¿Puedo saber cómo hacer esto en PostgreSQL?

Author: Erwin Brandstetter, 2013-06-04

4 answers

Este es un caso de uso perfecto para DISTINCT ON (Postgres extensión específica de la norma DISTINCT):

SELECT DISTINCT ON (category)
       id  -- , category, date -- add any other column (expression) from the same row
FROM   tbl
ORDER  BY category, "date" DESC;

Cuidado con el orden descendente. Si la columna puede ser NULA, es posible que desee agregar NULLS LAST:

DISTINCT ON es más simple y rápido. Explicación detallada en esta respuesta relacionada:

Para mesas grandes considere este enfoque alternativo:

Optimización del rendimiento para muchas filas por category:

 90
Author: Erwin Brandstetter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-05 11:31:40

Prueba este:

SELECT * FROM Table1 t1
JOIN 
(
   SELECT category, MAX(date) AS MAXDATE
   FROM Table1
   GROUP BY category
) t2
ON T1.category = t2.category
AND t1.date = t2.MAXDATE

Ver este SQLFiddle

 15
Author: hims056,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-04 09:25:24

Otro enfoque es usar la función de ventana first_value: http://sqlfiddle.com/#! 12 / 7a145/14

SELECT DISTINCT
  first_value("id") OVER (PARTITION BY "category" ORDER BY "date" DESC) 
FROM Table1
ORDER BY 1;

... aunque sospecho que la sugerencia de hims056 normalmente se desempeñará mejor donde estén presentes los índices apropiados.

Una tercera solución es:

SELECT
  id
FROM (
  SELECT
    id,
    row_number() OVER (PARTITION BY "category" ORDER BY "date" DESC) AS rownum
  FROM Table1
) x
WHERE rownum = 1;
 10
Author: Craig Ringer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-04 12:29:17

SELECCIONE id DEL GRUPO tbl POR gato CON MAX (fecha)

 -2
Author: Unmerciful,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-27 09:56:59