简体   繁体   中英

Query to get all rows grouped by a field value with a condition on another field

I have following query:

SELECT 
a.id_posicion,
a.profesional, 
MAX( a.fecha_hora ) AS fechaPosicion, 
a.latitud, 
a.longitud, 
b.tipo_profesional, 
b.nombre, 
b.apellidos,
c.tipo_profesional as tipoProfesional,
b.profile_image,
b.tel as tel, 
e.especialidad as especialidad_profesional,
b.ciudad as ciudad, 
b.departamento as departamento,
b.id_firebase as id_firebase 

FROM tb_ultima_posicion_pro a 

INNER JOIN users b ON b.id = a.profesional 

INNER JOIN tb_profesionales c ON c.id_profesionales = b.tipo_profesional

INNER JOIN tb_especialidades_profesional d ON d.profesional = b.id 

INNER JOIN tb_especialidades e ON d.especialidad = e.id_especialidad  

GROUP BY a.profesional 

ORDER BY fechaPosicion DESC

What I need is to get all records from the table tb_ultima_posicion_pro, grouped by the field profesional , which means that I get only a row for each profesional (that is ok), and for each profesional I need to get te row with the newest field fecha_hora , which is a datetime field.

What I am getting with this query is a row for each profesional (ok) but not the one with the newest fecha_hora field value.

Alternatively, You can first fetch the maximum fetch_hora by grouping the table tb_ultima_posicion_pro and then can join other tables -

SELECT a.id_posicion
      ,a.profesional
      ,am.fecha_hora AS fechaPosicion
      ,a.latitud
      ,a.longitud
      ,b.tipo_profesional
      ,b.nombre
      ,b.apellidos
      ,c.tipo_profesional as tipoProfesional
      ,b.profile_image
      ,b.tel as tel
      ,e.especialidad as especialidad_profesional
      ,b.ciudad as ciudad
      ,b.departamento as departamento
      ,b.id_firebase as id_firebase 
FROM tb_ultima_posicion_pro a
INNER JOIN (SELECT profesional
                  ,MAX(fecha_hora) AS fecha_hora
            FROM tb_ultima_posicion_pro 
            GROUP BY profesional) am ON a.profesional = am.profesional
                                    AND a.fecha_hora = am.fecha_hora
INNER JOIN users b ON b.id = a.profesional 
INNER JOIN tb_profesionales c ON c.id_profesionales = b.tipo_profesional
INNER JOIN tb_especialidades_profesional d ON d.profesional = b.id 
INNER JOIN tb_especialidades e ON d.especialidad = e.id_especialidad
ORDER BY fechaPosicion DESC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM