- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to multiply columns and then sum the rows with similar records like customer name?
To understand this, let us create a table with fields like ID, Customer Name, Items, Price. We will first multiply the items with price. After that the rows with similar records i.e. same customer name will get added.
Let us first create a table:
mysql> create table DemoTable ( CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY, CustomerName varchar(100), CustomerItems int, CustomerPrice int ); Query OK, 0 rows affected (0.54 sec)
Following is the query to insert some records in the table using insert command:
mysql> insert into DemoTable(CustomerName,CustomerItems,CustomerPrice)values('Larry',3,450); Query OK, 1 row affected (0.24 sec) mysql> insert into DemoTable(CustomerName,CustomerItems,CustomerPrice)values('Mike',2,550); Query OK, 1 row affected (0.42 sec) mysql> insert into DemoTable(CustomerName,CustomerItems,CustomerPrice)values('Larry',4,1000); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(CustomerName,CustomerItems,CustomerPrice)values('Larry',1,100); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(CustomerName,CustomerItems,CustomerPrice)values('Mike',5,200); Query OK, 1 row affected (0.71 sec)
Following is the query to display records from the table using select command:
mysql> select *from DemoTable;
This will produce the following output
+------------+--------------+---------------+---------------+ | CustomerId | CustomerName | CustomerItems | CustomerPrice | +------------+--------------+---------------+---------------+ | 1 | Larry | 3 | 450 | | 2 | Mike | 2 | 550 | | 3 | Larry | 4 | 1000 | | 4 | Larry | 1 | 100 | | 5 | Mike | 5 | 200 | +------------+--------------+---------------+---------------+ 5 rows in set (0.00 sec)
Here is the query to multiply columns (Items * Price) and then sum rows with similar record:
mysql> SELECT CustomerName, SUM( CustomerItems* CustomerPrice) AS TOTAL_PRICE FROM DemoTable GROUP BY CustomerName;
This will produce the following output
+--------------+-------------+ | CustomerName | TOTAL_PRICE | +--------------+-------------+ | Larry | 5450 | | Mike | 2100 | +--------------+-------------+ 2 rows in set (0.05 sec)
Advertisements