从重复的列值中获取相应最大值的 MySQL 查询


我们首先创建一个表 -

mysql> create table DemoTable(
   ProductName varchar(100),
   ProductPrice int
);
Query OK, 0 rows affected (0.68 sec)

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

mysql> insert into DemoTable values('Product-1',56);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Product-2',78);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values('Product-1',88);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Product-2',86);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('Product-1',45);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('Product-3',90);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('Product-2',102);
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values('Product-3',59);
Query OK, 1 row affected (0.13 sec)

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

mysql> select *from DemoTable;

这将产生以下输出 -

+-------------+--------------+
| ProductName | ProductPrice |
+-------------+--------------+
| Product-1   | 56           |
| Product-2   | 78           |
| Product-1   | 88           |
| Product-2   | 86           |
| Product-1   | 45           |
| Product-3   | 90           |
| Product-2   | 102          |
| Product-3   | 59           |
+-------------+--------------+
8 rows in set (0.00 sec)

以下是从重复的列值中获取相应最大值的查询。在此,我们查找 Product-1、Product-2 等重复列的最大 ProductPrice -

mysql> select ProductName,MAX(ProductPrice) from DemoTable group by ProductName;

这将产生以下输出 -

+-------------+-------------------+
| ProductName | MAX(ProductPrice) |
+-------------+-------------------+
| Product-1   | 88                |
| Product-2   | 102               |
| Product-3   | 90                |
+-------------+-------------------+
3 rows in set (0.00 sec)

更新于: 2019 年 9 月 27 日

152 次浏览

开启你的 职业生涯

完成课程取得认证

开始
广告