Sum Product Price Values in MySQL for Same Customers



For this, use SUM() along with GROUP BY. Let us first create a table −

mysql> create table DemoTable
(
   CustomerName varchar(100),
   Product_1_Price int,
   Product_2_Price int
);
Query OK, 0 rows affected (0.73 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('John',67,89);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('David',769,890);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('David',987,1000);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('John',900,111);
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------------+-----------------+-----------------+
| CustomerName | Product_1_Price | Product_2_Price |
+--------------+-----------------+-----------------+
| John         |              67 |              89 |
| David        |             769 |             890 |
| David        |             987 |            1000 |
| John         |             900 |             111 |
+--------------+-----------------+-----------------+
4 rows in set (0.00 sec)

Following is the query to SUM the values and display the result for the same customers −

mysql> select CustomerName,SUM(Product_1_Price) AS Total1,SUM(Product_2_Price) As Total2 from DemoTable group by CustomerName;

This will produce the following output −

+--------------+--------+--------+
| CustomerName | Total1 | Total2 |
+--------------+--------+--------+
| John         |    967 |    200 |
| David        |   1756 |   1890 |
+--------------+--------+--------+
2 rows in set (0.00 sec)
Updated on: 2019-09-27T07:22:26+05:30

447 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements