sql server - SQL Joint and Group two tables with SUM function -


so have 2 tables:

products product id | quantity  orderslines  product id | amount (multiple lines same id) 

i want join 2 tables. result should - product id (group by), quantity , sum of amounts orderslines table.

i got far:

select p.productid, p.quantity, sum(ol.amount) atbl_sales_products p left join atbl_sales_orderslines ol on ol.productid = p.productid  group p.productid 

this produces error:

column 'atbl_sales_products.quantity' invalid in select list because not contained in either aggregate function or group clause.

thanks help!

well, there 2 ways write depending on want

adding quantity aggregate...

select     p.productid,     sum(p.quantity),     sum(ol.amount) atbl_sales_products p left join atbl_sales_orderslines ol on ol.productid = p.productid  group p.productid 

adding quantity grouping

select     p.productid,     p.quantity,     sum(ol.amount) atbl_sales_products p left join atbl_sales_orderslines ol on ol.productid = p.productid  group p.productid, p.quantity --based on comment having sum(ol.amount) > p.quantity 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -