I have the following columns in a table:
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With