gpt4 book ai didi

MySQL 分组依据和不确定结果

转载 作者:行者123 更新时间:2023-11-29 16:42:44 25 4
gpt4 key购买 nike

我一直在研究如何正确使用 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 |
|---------------------|------------------|-------------------------|

我想要的输出:(以同一行的正确 carhash 作为最短试驾时间)

|---------------------|------------------|-------------------------|
| ID | carhash | testdrivetime |
|---------------------|------------------|-------------------------|
| 12 | 345 | 2:22 |
|---------------------|------------------|-------------------------|

最佳答案

  • 在子选择查询 ( Derived Table ) 中,确定最小值 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

关于MySQL 分组依据和不确定结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53258165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com