Stack Overfolow
Stack Overfolow

Reputation: 671

Getting the sum of quantity by product id

I'm struggling to get some results from my database. I have a table like this:

    ID ID_INVOICE PRODUCT QUANTITY PRODUCT_ID
    ------------------------------------------
     1    1          aaa     3       2
     2    1          bbb     2       3
     3    1          ccc     1       4
     4    2          bbb     3       3
     5    2          aaa     3       2

So after the query I would like to get something like

   aaa  6
   bbb  5
   ccc  1

The query is based on the ID_INVOICE so far I've tried this:

  SELECT product, sum(quantity) 
  FROM product 
  WHERE invoice_id = @p1

Upvotes: 2

Views: 1985

Answers (1)

Mahmoud Gamal
Mahmoud Gamal

Reputation: 79979

Add a GROUP BY product clause, like so:

SELECT  product, sum(quantity) 
FROM product 
WHERE invoice_id = @p1
GROUP BY product;

SQL Fiddle Demo

Upvotes: 4

Related Questions