Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add values of the same item in a column?

Tags:

sql

I have the following columns in a table:

  1. Product Name
  2. Quantity
  3. Description

I want to add the quantities of the product if the name of the product is same. For example if I have product with the same name twice, I want the total quantities of the products to be added and get a result.

This is the table and I want to add the quantities of the same item:

Name            Quantity   Description
Pen              3 
Pencil           2
Pen              6
Eraser           7
Eraser           6

For exmaple:

  • I have pen twice and so want to add (3+6) and the display the total as 9, and ...
  • I have eraser twice (7+6), so the total should be 13.
like image 773
user1562991 Avatar asked Jul 30 '12 13:07

user1562991


1 Answers

The solution is GROUP BY clause:

SELECT Name, SUM(Quantity) 
FROM Table
GROUP BY Name

GROUP BY is used in an SQL query to group rows together for aggregation purposes. For example: If your input table had rows:

ItemName       Qty
Pen            4
Pencil         7
Pen            6

SQL Code:

SELECT ItemName, SUM(Qty) 
FROM Table
GROUP BY ItemName

Using GROUP BY ItemName in your query would give you the output:

ItemName       Qty
Pen            10
Pencil         7
like image 50
Snow Blind Avatar answered Nov 15 '22 03:11

Snow Blind