我有一个临时表,它是从一个更大的表中派生出来的。
+-----+----------+---------+
| id | phone | attempt |
+-----+----------+---------+
| 1 | 12345678 | 15 |
| 2 | 87654321 | 0 |
| 4 | 12345678 | 16 |
| 5 | 12345678 | 14 |
| 10 | 87654321 | 1 |
| 11 | 87654321 | 2 |
+-----+----------+---------+
我需要找到与对每个电话号码进行的最高尝试相对应的 ID(唯一)。电话和尝试不是唯一的。
SELECT id, MAX(attempt) FROM temp2 GROUP BY phone
上面的查询没有返回相应最大尝试的id。
最佳答案
试试这个:
select
t.*
from temp2 t
inner join (
select phone, max(attempt) attempt
from temp2
group by phone
) t2 on t.phone = t2.phone
and t.attempt = t2.attempt;
它将返回具有给定数字的最大尝试次数的行。
请注意,如果尝试次数与该电话的最大尝试次数相同,则如果电话有多行,这将返回多个 ID。
关于mysql - MySQL中group by语句后选择对应的非聚合列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41886638/