我已经研究了这个问题,但我仍然在努力编写一个有效的查询。非常感谢任何帮助。
表
+----------+-------------+
| 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;
答案 0 :(得分:2)
这只是一个聚合(不需要连接):
select u.username, max(u.signup_date)
from users u
group by u.username
having count(*) > 1;
答案 1 :(得分:0)
试试这个:
SELECT username, MAX(signup_date)
FROM users
GROUP BY username
HAVING COUNT(username) > 1