选择查询以显示具有最大日期的重复值

为此,请使用GROUP BY和HAVING。让我们首先创建一个表-

mysql> create table DemoTable
   (
   StudentName varchar(100),
   DueDate date
   );

示例

使用插入命令在表中插入一些记录-

mysql> insert into DemoTable values('John','2019-01-11');
mysql> insert into DemoTable values('Chris','2019-02-11');
mysql> insert into DemoTable values('Chris','2019-03-11');
mysql> insert into DemoTable values('John','2019-04-11');
mysql> insert into DemoTable values('Bob','2019-05-11');
mysql> insert into DemoTable values('Bob','2019-06-11');
mysql> insert into DemoTable values('Robert','2019-07-11');
mysql> insert into DemoTable values('Robert','2019-08-11');
mysql> insert into DemoTable values('Robert','2019-09-11');

使用select语句显示表中的所有记录-

mysql> select *from DemoTable;

输出结果

+-------------+------------+
| 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)

以下是查询以显示具有最大日期的重复值-

mysql> select tbl.StudentName,max(tbl.DueDate) from DemoTable tbl group by tbl.StudentName
having count(*) > 1;

输出结果

+-------------+------------------+
| 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)