简体   繁体   中英

sql select distinc where max date

I have 3 tables "maintenances", "cars", "users" . I want to select all data from table maintenance with a distinct car_id and the last record for each distinct (based on max maintenance_date)

SELECT
     m. * , u.username, c.Model, c.Make, c.License, c.Milage, COUNT( m.process_id ) AS count_nr
    FROM
      maintenances AS m

    LEFT JOIN users AS u ON u.id = m.user_id
    LEFT JOIN cars AS c ON c.id = m.car_id

    WHERE
    maintenance_date = (SELECT MAX(maintenance_date) FROM maintenances WHERE car_id = m.car_id)

The problem is that this query returns only one record which has the max date from all records. I want all records (distinct car_id and from records with the same car_id to display only values for max(maintenance_date))

add GROUP BY u.username .

 WHERE
maintenance_date = (SELECT MAX(maintenance_date) FROM maintenances WHERE car_id = m.car_id)
 GROUP BY u.username

This is your query:

SELECT m. * , u.username, c.Model, c.Make, c.License, c.Milage, COUNT( m.process_id ) AS count_nr
----------------------------------------------------------------^
FROM maintenances AS m LEFT JOIN
     users AS u
     ON u.id = m.user_id LEFT JOIN
     cars AS c
     ON c.id = m.car_id
WHERE maintenance_date = (SELECT MAX(maintenance_date) FROM maintenances WHERE car_id = m.car_id);

It is an aggregation query. Without a group by , only one row is returned (all the rows are in one group). So, add the group by :

SELECT m. * , u.username, c.Model, c.Make, c.License, c.Milage, COUNT( m.process_id ) AS count_nr
FROM maintenances AS m LEFT JOIN
     users AS u
     ON u.id = m.user_id LEFT JOIN
     cars AS c
     ON c.id = m.car_id
WHERE maintenance_date = (SELECT MAX(m2.maintenance_date) FROM maintenances m2 WHERE m2.car_id = m.car_id);
GROUP BY c.id

I also fixed the correlation statement, to be clear that it is correlated to the outer query.

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