AGRUPAR POR con MAX (FECHA) [duplicar]


Esta pregunta ya tiene una respuesta aquí:

Estoy tratando de enumerar el último destino (hora máxima de salida) para cada tren en una tabla, por ejemplo :

Train    Dest      Time
1        HK        10:00
1        SH        12:00
1        SZ        14:00
2        HK        13:00
2        SH        09:00
2        SZ        07:00

El resultado deseado debe ser:

Train    Dest      Time
1        SZ        14:00
2        HK        13:00

He intentado usar

SELECT Train, Dest, MAX(Time)
FROM TrainTable
GROUP BY Train

Por I got a "ora-00979 no es un GRUPO POR expresión" error diciendo que debo incluir 'Dest' en mi grupo por declaración. Pero seguramente eso no es lo que quiero...

¿Es posible hacerlo en una línea de SQL?

Author: Pacerier, 2010-08-16

6 answers

No puede incluir columnas no agregadas en su conjunto de resultados que no estén agrupadas. Si un tren solo tiene un destino, simplemente agregue la columna destino a su cláusula group by; de lo contrario, debe reconsiderar su consulta.

Intenta:

SELECT t.Train, t.Dest, r.MaxTime
FROM (
      SELECT Train, MAX(Time) as MaxTime
      FROM TrainTable
      GROUP BY Train
) r
INNER JOIN TrainTable t
ON t.Train = r.Train AND t.Time = r.MaxTime
 121
Author: Oliver Hanappi,
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
2015-04-30 06:23:36
SELECT train, dest, time FROM ( 
  SELECT train, dest, time, 
    RANK() OVER (PARTITION BY train ORDER BY time DESC) dest_rank
    FROM traintable
  ) where dest_rank = 1
 135
Author: Thilo,
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
2010-08-16 07:42:11

Aquí hay un ejemplo que solo usa un join izquierdo y creo que es más eficiente que cualquier grupo por método: ExchangeCore Blog

SELECT t1.*
FROM TrainTable t1 LEFT JOIN TrainTable t2
ON (t1.Train = t2.Train AND t1.Time < t2.Time)
WHERE t2.Time IS NULL;
 69
Author: Joe Meyer,
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
2015-10-12 11:43:47

Otra solución:

select * from traintable
where (train, time) in (select train, max(time) from traintable group by train);
 11
Author: Claudio Negri,
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
2014-06-23 16:07:31

Siempre y cuando no haya duplicados (y los trenes tienden a llegar solo a una estación a la vez)...

select Train, MAX(Time),
      max(Dest) keep (DENSE_RANK LAST ORDER BY Time) max_keep
from TrainTable
GROUP BY Train;
 8
Author: Gary Myers,
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
2010-08-16 23:24:39

Sé que llego tarde a la fiesta, pero prueba esto...

SELECT 
    `Train`, 
    `Dest`,
    SUBSTRING_INDEX(GROUP_CONCAT(`Time` ORDER BY `Time` DESC), ",", 1) AS `Time`
FROM TrainTable
GROUP BY Train;

Src: Documentación del Grupo Concat

Editar: sintaxis sql fija

 3
Author: Gravy,
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
2016-01-14 13:29:16