我一直在研究正确使用MySQL Group By和Joins以避免其他列中未聚合值的不确定值。现在,通过下面的查询,在按客户ID分组时,如何确保以最少的试驾时间选择正确的Vin号码?基本上,如何确保整个行都与最短的测试行驶时间相关?
SELECT t1.ID AS CUSTOMERID, t1.carhash,
MIN(t1.testdrivetime) AS testdrivetime,
t2.vinnumber AS vinnumber
FROM TABLE1 t1
INNER JOIN TABLE2 t2 ON t2.vinnumber = t1.carhash
INNER JOIN (SELECT t1.ID, MIN(testdrivetime) AS testdrivetime
FROM TABLE1
GROUP BY t1.ID) f
ON f.ID = t1.ID AND f.testdrivetime = t1.testdrivetime
GROUP BY ID
|---------------------|------------------|-------------------------|
| ID | carhash | testdrivetime |
|---------------------|------------------|-------------------------|
| 12 | 345 | 2:22 |
|---------------------|------------------|-------------------------|
| 12 | 277 | 4:51 |
|---------------------|------------------|-------------------------|
|---------------------|------------------|-------------------------|
| ID | carhash | testdrivetime |
|---------------------|------------------|-------------------------|
| 12 | 277 | 2:22 |
|---------------------|------------------|-------------------------|
|---------------------|------------------|-------------------------|
| ID | carhash | testdrivetime |
|---------------------|------------------|-------------------------|
| 12 | 345 | 2:22 |
|---------------------|------------------|-------------------------|
答案 0 :(得分:0)
testdrivetime
的最小ID
值。ID
和testdrivetime
将结果集返回到主表,以获取与最小testdrivetime
值相对应的行。尝试:
SELECT
t.*
FROM your_table AS t
JOIN
(
SELECT
ID,
MIN(testdrivetime) AS min_testdrivetime
FROM your_table
GROUP BY ID
) AS dt
ON dt.ID = t.ID AND
dt.min_testdrivetime = t.testdrivetime