在 MySQL 中用重复的列值选择某列的最小行值


我们首先创建一个表 -

mysql> create table DemoTable1875
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Class varchar(20),
   Amount int
   );
Query OK, 0 rows affected (0.00 sec)

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

mysql> insert into DemoTable1875(Class,Amount) values('X',750);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1875(Class,Amount) values('X',140);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1875(Class,Amount) values('X',450);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1875(Class,Amount) values('Y',6780);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1875(Class,Amount) values('Z',1350);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1875(Class,Amount) values('Z',2050);
Query OK, 1 row affected (0.00 sec)

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

mysql> select * from DemoTable1875;

这将产生以下输出 -

+----+-------+--------+
| Id | Class | Amount |
+----+-------+--------+
|  1 | X     |    750 |
|  2 | X     |    140 |
|  3 | X     |    450 |
|  4 | Y     |    6780 |
|  5 | Z     |    1350 |
|  6 | Z     |    2050 |
+----+-------+--------+
6 rows in set (0.00 sec)

以下是选择行的查询

mysql> select Class,Min(Amount) from DemoTable1875 group by Class;

这将产生以下输出 -

+-------+-------------+
| Class | Min(Amount) |
+-------+-------------+
| X     |         140 |
| Y     |        6780 |
| Z     |        1350 |
+-------+-------------+
3 rows in set (0.00 sec)

更新日期:2020-12-27

519 次浏览

开启你的 职业

通过完成课程获得认证

开始
广告