[英]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. 但这似乎不允许
MAX
函数正常工作。 It does not always contain the actual maximum value for mileage
它并不总是包含
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). 您应该将转换
mileage
和oil_change
列数字类型(我建议INT
根据所提供的数据样本)。
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 关于Venk
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.