, GROUP BY , GROUP BY.
:
SELECT u.*
FROM users u
INNER JOIN (
SELECT xName, MAX(xDatetime) max_time
FROM users
GROUP BY xName
) sub_u ON (sub_u.xName = u.xName AND
u.xDateTime = sub_u.max_time);
:
CREATE TABLE users (id int, xName varchar(100), xDateTime datetime);
INSERT INTO users VALUES (1, 'a', '2010-03-11 00:00:00');
INSERT INTO users VALUES (2, 'a', '2010-03-11 01:00:00');
INSERT INTO users VALUES (3, 'a', '2010-03-11 02:00:00');
INSERT INTO users VALUES (4, 'b', '2010-03-11 01:00:00');
INSERT INTO users VALUES (5, 'b', '2010-03-11 02:00:00');
INSERT INTO users VALUES (6, 'b', '2010-03-11 03:00:00');
INSERT INTO users VALUES (7, 'c', '2010-03-11 06:00:00');
INSERT INTO users VALUES (8, 'c', '2010-03-11 05:00:00');
+
| id | xName | xDateTime |
+
| 3 | a | 2010-03-11 02:00:00 |
| 6 | b | 2010-03-11 03:00:00 |
| 7 | c | 2010-03-11 06:00:00 |
+
If you want to order the result set in the field max_time, just add ORDER BY u.xDateTime DESCto the end of the query.
source
share