Search code examples
mysqlsqljoinselectinner-join

Sql query using joins to find sum of quantity


Product table

billtran table

Here,in billtran table the productid=1 is repeated twice

I want to find the sum(billtran.quantity) of each productid separately

I want this output,the out expected my me is

select Query1:

 select name,billtran.quantity from product inner join billtran on product.id=billtran.productid where product.id in(select id from product)

Output of select query1


Solution

  • Per comment:

    select name, SUM(billtran.quantity) from product inner join billtran on product.id=billtran.productid where product.id in(select id from product)
    GROUP BY NAME
    

    My additions in caps

    Note: where product.id in(select id from product) is an entirely useless where clause and should be removed. Queries don't have to have a where clause and don't need one that says a table id should be in all the ids in that table (always true)

    I would hence have written this one as:

    SELECT
      p.name,
      SUM(b.quantity) as sumof_quantity
    FROM 
      product p
      INNER JOIN billtran b ON p.id=b.productid 
    GROUP BY 
      p.name