2015-10-07 87 views
2

我已經研究過這個問題,但我仍然在努力編寫一個有效的查詢。任何幫助是極大的讚賞。選擇查詢以顯示最大日期的重複

+----------+-------------+ 
| username | signup_date | 
+----------+-------------+ 
| user1 | 2010-01-15 | 
| user1 | 2010-02-15 | 
| user2 | 2010-03-15 | 
| user3 | 2010-04-15 | 
| user3 | 2010-05-15 | 
| user4 | 2010-06-15 | 
| user5 | 2010-07-15 | 
| user6 | 2010-08-15 | 
| user6 | 2010-09-15 | 
| user6 | 2010-10-15 | 
+----------+-------------+ 

我想寫一個查詢,返回只重複的用戶名值和最近signup_date。

預期的效果

+----------+-------------+ 
| username | signup_date | 
+----------+-------------+ 
| user1 | 2010-02-15 | 
| user3 | 2010-05-15 | 
| user6 | 2010-10-15 | 
+----------+-------------+ 

到目前爲止,我有這個,但它並不過濾下來signup_date的最大值。相反,它會返回每個重複的行。

SELECT users.username, users.signup_date 
FROM users 
INNER JOIN (SELECT username FROM users 
GROUP BY username HAVING count(id) > 1) dup ON users.username = dup.username; 

回答

2

這僅僅是一個聚合(沒有聯接需要):

select u.username, max(u.signup_date) 
from users u 
group by u.username 
having count(*) > 1; 
+0

謝謝!!正是我在找什麼。想出答案可能很簡單。令人驚訝的是得到如此迅速的迴應。 – newbie

0

試試這個:

SELECT username, MAX(signup_date) 
FROM users 
GROUP BY username 
HAVING COUNT(username) > 1