Syntax error MySQL query to sum rows having repeated corresponding Id

MySQL query to sum rows having repeated corresponding Id



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)
Updated on: 2019-09-03T14:39:00+05:30

265 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements