Select minimum row value from a column with corresponding duplicate column values in MySQL

MySQLMySQLi Database

Let us first create a table −

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 some records in the table using insert command −

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)

Display all records from the table using select statement −

mysql> select * from DemoTable1875;

This will produce the following output −

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

Following is the query to select row

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

This will produce the following output −

+-------+-------------+
| Class | Min(Amount) |
+-------+-------------+
| X     |         140 |
| Y     |        6780 |
| Z     |        1350 |
+-------+-------------+
3 rows in set (0.00 sec)
raja
Published on 27-Dec-2019 10:47:04
Advertisements