Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL how to return column values with same name only once

I have a table containing 3 columns consisting of a product (varchar), quantity(integer), price(integer). I want to get the total price of the products and return the product and the total price and ordered by descending alphabetical order. But if the product is repeated I only want to return the product once with its total price.

Heres the table:

product quantity price
Pencil 2 4
Notebook 3 5
Notebook 5 5

In this case desired output would be :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

product totalprice
Notebook 40
Pencil 8

My current output is this:

product totalprice
Notebook 15
Notebook 25
Pencil 8

My query is the following:

SELECT product, quantity * price AS totalprice
FROM schoolproducts
ORDER BY product DESC

>Solution :

This is a case for aggregation:

SELECT product, sum(quantity * price) AS totalprice
FROM schoolproducts
GROUP BY product
ORDER BY product DESC
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading