[英]Select List is not in Group By Clause and Contains non-aggregated column
[英]Select corresponding non-aggregated column after group by statment in MySQL
我有一個臨時表,我從一個更大的表中派生出來。
+-----+----------+---------+
| 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。
作為@GurV給出的答案的替代方法,您還可以使用相關子查詢來解決此問題:
SELECT t1.*
FROM temp2 t1
WHERE t1.attempt = (SELECT MAX(t2.attempt) FROM temp2 t2 WHERE t2.phone = t1.phone)
這樣做的好處是不那么冗長。 但我可能會選擇加入選項,因為它可以更好地擴展到大型數據集。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.