MySQL query to sum rows having repeated corresponding Id

MySQLMySQLi Database

To sum, you can use aggregate function SUM(). Let us first create a table −

mysql> create table DemoTable850(
   Id int,
   Price int
);
Query OK, 0 rows affected (0.54 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable850 values(1,90);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable850 values(2,100);
Query OK, 1 row affected (0.55 sec)
mysql> insert into DemoTable850 values(2,50);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable850 values(1,80);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable850 values(1,60);
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable850;

This will produce the following output −

+------+-------+
| Id   | Price |
+------+-------+
| 1    | 90    |
| 2    | 100   |
| 2    | 50    |
| 1    | 80    |
| 1    | 60    |
+------+-------+
5 rows in set (0.00 sec)

Following is the query to sum rows having repeated values −

mysql> select Id,SUM(Price) from DemoTable850 where Id=1;

This will produce the following output −

+------+------------+
| Id   | SUM(Price) |
+------+------------+
| 1    | 230       |
+------+------------+
1 row in set (0.00 sec)
raja
Published on 03-Sep-2019 12:07:02
Advertisements