MySQL query to multiply values of two rows and add the result


For this, use aggregate function SUM(). Within this method, multiply the row values. Let us first create a table −

mysql> create table DemoTable(
   ProductQuantity int,
   ProductPrice int
);
Query OK, 0 rows affected (0.48 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(10,9);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(6,20);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(7,100);
Query OK, 1 row affected (0.08 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------------+--------------+
| ProductQuantity | ProductPrice |
+-----------------+--------------+
| 10              |            9 |
| 6               |           20 |
| 7               |          100 |
+-----------------+--------------+
3 rows in set (0.00 sec)

Following is the query to multiply values of two rows and add the result −

mysql> select SUM(ProductQuantity*ProductPrice) AS Total_Value from DemoTable;

This will produce the following output −

+-------------+
| Total_Value |
+-------------+
| 910         |
+-------------+
1 row in set (0.00 sec)

Updated on: 03-Sep-2019

825 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements