简体   繁体   中英

Finding Max() values via foreign key

Consider this database structure:

 __________                 __________
| Trucks   |               | Mileage  |
|__________|__________     |__________|________________________
| ID    | DRIVER      |    | TRUCK_ID  | MILEAGE  | OIL_CHANGE |
|---------------------|    |-----------------------------------|
| 1     | Tony        |    | 1         | 100000     105000     |
| 2     | George      |    | 2         | 6020       10020      |
| 3     | Mary        |    | 3         | 37798      41000      |
|_____________________|    | 3         | 41233      47200      |
                           | 3         | 49000                 |
                           |___________________________________|

I want to end up with a result set containing the maximum miles and maximum oil_change for each driver.

_________________________________
| 1  | Tony  |  100000 | 105000 |
| 2  | George|  6020   | 10020  |
| 3  | Mary  |  49000  | 47200  |
|_______________________________|

This is what I have tried so far:

SELECT t.*, MAX(m.mileage) AS mileage, MAX(m.oil_change) AS oil_change
FROM trucks t
LEFT JOIN mileage m ON t.id = m.truck_id
GROUP BY t.id

But this doesn't seem to allow the MAX function to work properly. It does not always contain the actual maximum value for mileage

Got it! Your mileage column must be defined as a character type, not a numeric type! When than happens, order is done alphabetically, not by value.

You should convert your mileage and oil_change columns to a numeric type (I'd recommend INT based on the data sample provided).

While you don't convert them, this will work:

SELECT t.*, MAX(cast(m.mileage as int)) AS mileage, 
            MAX(cast(m.oil_change as int)) AS oil_change
FROM trucks t
LEFT JOIN mileage m ON t.id = m.truck_id
GROUP BY t.id

The below queries should work for your question.

SELECT T.DRIVER,MIN(MILEAGE) AS MIN_MILEAGE,MIN(OIL_CHANGE) AS MIN_OIL_CHANGE
FROM TRUCKS T INNER JOIN MILEAGE M
ON T.ID = M.TRUCK_ID
GROUP BY T.DRIVER;


SELECT T.DRIVER,MAX(MILEAGE) AS MAX_MILEAGE,MAX(OIL_CHANGE) AS MAX_OIL_CHANGE
FROM TRUCKS T INNER JOIN MILEAGE M
ON T.ID = M.TRUCK_ID
GROUP BY T.DRIVER;

Regards Venk

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