Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine SELECT DISTINCT and SUM()

Tags:

sql

select

I have a table like given bellow, in Oracle:

[Products]
Product_ID | Product_NME | Product_SUP | Quantity
=================================================
    1         Apple         USA           100
    2         Fish          Japan          50
    3         Wine          Italy          10
    4         Apple         China          30
    5         Fish          Germany        10

I need a query that will find the full Quantity for every Product_NME by DISTINCT.

The expected result should be:

  • apple 130
  • fish 60
  • wine 10

I've tried to modify it like the one shown here as:

SELECT
    distinct(Product_NME, Product_SUP), sum(Quantity)
FROM
    Products

But it's not my case. Also I've tried this one:

SELECT DISTINCT  Product_NME
FROM Products 
UNION
SELECT SUM(Quantity) FROM Products 

But is also not working.

Can anyone help me with this?

  • Thanks
like image 544
ekostadinov Avatar asked Dec 20 '22 11:12

ekostadinov


1 Answers

DISTINCT is not the clause you are looking for!

GROUP BY is.

The following query will return with all products and the total quantity for each one.

SELECT
  Product_NME
  , SUM(Quantity) AS TotalQuantity
FROM
  Products 
GROUP BY
  Product_NME
like image 72
Pred Avatar answered Jan 04 '23 04:01

Pred