Sử dụng GROUP BY và HAVING để lọc nhóm trùng lặp và lấy ngày lớn nhất.
Tạo bảng demo
mysql> create table DemoTable (
StudentName varchar(100),
DueDate date
);
Query OK, 0 rows affected (0.72 sec)
Chèn dữ liệu có trùng lặp StudentName với DueDate khác nhau
mysql> insert into DemoTable values('John', '2019-01-11');
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable values('Chris', '2019-02-11');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values('Chris', '2019-03-11');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('John', '2019-04-11');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Bob', '2019-05-11');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('Bob', '2019-06-11');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('Robert', '2019-07-11');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('Robert', '2019-08-11');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('Robert', '2019-09-11');
Query OK, 1 row affected (0.15 sec)
Hiển thị tất cả 9 bản ghi
mysql> select * from DemoTable;
Kết quả
+-------------+------------+ | StudentName | DueDate | +-------------+------------+ | John | 2019-01-11 | | Chris | 2019-02-11 | | Chris | 2019-03-11 | | John | 2019-04-11 | | Bob | 2019-05-11 | | Bob | 2019-06-11 | | Robert | 2019-07-11 | | Robert | 2019-08-11 | | Robert | 2019-09-11 | +-------------+------------+ 9 rows in set (0.00 sec)
Truy vấn: Nhóm theo tên, lấy MAX(DueDate), chỉ nhóm có count > 1
mysql> select tbl.StudentName, max(tbl.DueDate) from DemoTable tbl group by tbl.StudentName having count(*) > 1;
Kết quả - Mỗi tên trùng lặp chỉ hiện 1 lần kèm ngày muộn nhất
+-------------+------------------+ | StudentName | max(tbl.DueDate) | +-------------+------------------+ | John | 2019-04-11 | | Chris | 2019-03-11 | | Bob | 2019-06-11 | | Robert | 2019-09-11 | +-------------+------------------+ 4 rows in set (0.00 sec)
Giải thích:
GROUP BY StudentName: Gom nhóm các hàng cùng tên.MAX(DueDate): Lấy ngày lớn nhất (muộn nhất) trong mỗi nhóm.HAVING COUNT(*) > 1: Chỉ giữ nhóm xuất hiện ≥ 2 lần (trùng lặp).
Ứng dụng: Tìm đơn hàng mới nhất của khách hàng lặp lại, lần kiểm tra y tế gần nhất, v.v.