Get rows with GROUP BY in MySQL?


Let us first create a table −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Subject varchar(20),
   Price int
   );
Query OK, 0 rows affected (0.64 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Subject,Price) values('MySQL',456);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(Subject,Price) values('MySQL',456);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(Subject,Price) values('MongoDB',56);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(Subject,Price) values('MongoDB',60);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(Subject,Price) values('Java',100);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(Subject,Price) values('Java',130);
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+----+---------+-------+
| Id | Subject | Price |
+----+---------+-------+
| 1  | MySQL   | 456   |
| 2  | MySQL   | 456   |
| 3  | MongoDB | 56    |
| 4  | MongoDB | 60    |
| 5  | Java    | 100   |
| 6  | Java    | 130   |
+----+---------+-------+
6 rows in set (0.00 sec)

Here is the query to get rows with GROUB BY in MySQL −

mysql> select sum(Price) AS Total, Subject from DemoTable group by Subject;

Output

+-------+---------+
| Total | Subject |
+-------+---------+
| 912   | MySQL   |
| 116   | MongoDB |
| 230   | Java    |
+-------+---------+
3 rows in set (0.04 sec)
raja
Published on 14-Jun-2019 11:08:31
Advertisements