SQL Grouping using left join - sql

I have 2 tables with related data. One table is for products and the other price. In the price table one product may appear several times. How can I return the result by grouping.
Below is my Query but the output is not with Group
SELECT distinct
p.Product,
p.Qty,
MAX(pr.netprice)
FROM Products p
LEFT OUTER JOIN Price pr ON p.Product=pr.Product
WHERE p.brand=''
GROUP BY p.Product, p.Qty

You should probably leave the Qty out of the group by, like this:
SELECT p.Product,
MAX(pr.netprice)
FROM Products p
LEFT OUTER JOIN Price pr ON p.Product=pr.Product
WHERE p.brand=''
GROUP BY p.Product

Related

using subquery in order to join columns from two tables

i started learning SQL and there is something i dont understand
i want to take the columns product_id and product_name from Production.products
and join it with the quantity column from the Production.stocks table
but instead of using join i want to use a subquery.
this is the code i wrote so far:
and i don't understand why it isn't working :(
SELECT P.product_id, P.product_name,(
SELECT S.quantity
FROM Production.stocks AS S
WHERE S.product_id = P.product_id)
FROM Production.products as P;
First, let's clear up the fact that it is not recommended to use a subquery at all. Do it only for your own research reasons; if you have performance or code clarity in mind, go with the simple join.
When you make a subquery on the SELECT clause by enclosing it in parenthesis, you are forcing the result to be one single value. If not, you get the error you receive.
Usually, subqueries are used in the FROM clause, where they should be given a name and then represent a table. Like this:
SELECT P.product_id, P.product_name,S.quantity
FROM Production.products as P
inner join
(
SELECT quantity
FROM Production.stocks
) as S on S.product_id = P.product_id
You can see from the simplicity of the subquery of how little use it is.
You can use SUM keyword for prevent error and give you total quatity.
SELECT P.product_id, P.product_name,(
SELECT SUM(S.quantity)
FROM Production.stocks AS S
WHERE S.product_id = P.product_id)
FROM Production.products as P;
I don't see a need at all for a subquery.
If the products are unique entities then surely a join onto the stocks table and doing a sum on the quantity would be more beneficial in terms of query performance
SELECT
Production.Products.Product_id,
Production.Products.product_name,
SUM(Production.Stocks.quantity) AS Quantity
FROM
Production.Products
LEFT JOIN
Production.Stocks
ON
Production.Stocks.product_id = Production.Products.product_id
GROUP BY
Production.Products.product_id,
Production.Products.product_name
If you need it to quote stock quantities by store then you need to add an addition join onto stores and add the store to the select and group by clause like so
SELECT
Production.Products.Product_id,
Production.Products.product_name,
Sales.Stores.store_name,
SUM(Production.Stocks.quantity) AS Quantity
FROM
Production.Products
LEFT JOIN
Production.Stocks
ON
Production.Stocks.product_id = Production.Products.product_id
LEFT JOIN
Sales.Stores
ON
Production.Stocks.store_id = Sales.Stores.store_id
GROUP BY
Production.Products.product_id,
Production.Products.product_name,
Sales.Stores.store_name
Hope that helps
did you mean select all data from products table and show quantity column for each product?
SELECT P.product_id, P.product_name, isnull(s.quantity, 0) as Quantity
FROM Production.products as P
left join Production.stocks AS S
on p.product_id = S.product_id
if you have one to many relation with Products and Stocks you should use subquery like this
SELECT P.product_id, P.product_name, isnull(s.quantity, 0) as Quantity
FROM Production.products as P
left join (
select product_id, sum(quantity) as Quantity
from Production.stocks
group by product_id)
as S on p.product_id = S.product_id
it will be produced aggregated sum value for quantity field

Triple Table Join with Subtraction

I have 3 tables (production, sales, wastage)
All 3 tables have the columns: Product and Quantity
I need a query statement that will join all 3 tables in the following manner:production - sales - wastage Grouped by Product
Thanks in advance for the tips and tricks :)
Combine tables using left join, group by product and get total quantity by substracting values assuming that there can be no record for a given product within sales or wastage tables and then count them as 0.
select p.product, sum(p.quantity - coalesce(s.quantity,0) - coalesce(w.quantity,0)) as qty
from production p
left join sales s on p.product = s.product
left join wastage w on p.product = w.product
group by p.product
You can group each table individually and then [left] join them:
SELECT p.product, p_quantity - COALESCE(s_quantity, 0) - COALESCE(w_quantity, 0)
FROM (SELECT product, SUM(quantity) AS p_quantity
FROM production
GROUP BY product) p
LEFT JOIN (SELECT product, SUM(quantity) AS s_quantity
FROM sales
GROUP BY product) s ON p.product = s.product
LEFT JOIN (SELECT product, SUM(quantity) AS w_quantity
FROM wastage
GROUP BY product) w ON p.product = w.product

Sql Table Left outer join result Group By

Product1
Purchase quantity from 3 invoices are 50+100+50 = 200 and
Sale quantity from 1 invoice is 10
I am using below code for getting the result as
Total Purchase - Total Sale = Closing Qty
200 - 10 = 290
but I am getting the wrong result as shown in the attached image:
Please guide me to correct my code
SELECT
P.PRODUCT as PRODUCTNAME,
P.QUANTITY AS PURCHASE,
ISNULL(S.QUANTITY, 0) AS SALE,
ISNULL(P.QUANTITY, 0) - ISNULL(s.QUANTITY, 0) AS CLOSINGQTY
FROM
[PurchaseData] P
LEFT OUTER JOIN
[DeliveryData1] S ON P.Product = s.PRODUCT
When working with aggregates from different tables, don't join the tables and aggregate then, but aggregate first and join the aggregates:
select
p.product as productname,
p.sum_quantity as purchase,
coalesce(s.sum_quantity, 0) as sale,
p.sum_quantity - coalesce(s.sum_quantity, 0) as closingqty
from
(
select product, sum(quantity) as sum_quantity
from purchasedata
group by product
) p
left join
(
select product, sum(quantity) as sum_quantity
from deliverydata1
group by product
) s on s.product = p.product;
I've replaced ifnull with coalesce, so the query is fully standard SQL compliant.
If you want the final result you should use sum and group by
SELECT
P.PRODUCT as PRODUCTNAME,
sum(P.QUANTITY AS PURCHASE),
sum(isnull(S.QUANTITY,0)) AS SALE,
sum(isnull(P.QUANTITY,0))-sum(isnull(s.QUANTITY,0)) AS CLOSINGQTY
FROM [PurchaseData] P LEFT OUTER JOIN [DeliveryData1] S ON P.Product = s.PRODUCT
GROUP BY P.PRODUCT
If I understand correctly, you have a problem because you have multiple purchase records for a given product. If that is the case, then just aggregate before the JOIN:
SELECT p.*, COALESCE(S.QUANTITY, 0) AS SALE,
COALESCE(P.QUANTITY, 0)-COALESCE(s.QUANTITY, 0) AS CLOSINGQTY
FROM (SELECT p.product, p.quantity
FROM PurchaseData P
GROUP BY p.product
) p LEFT OUTER JOIN
DeliveryData1 S
ON P.product = s.producct;
Actually, I'm unclear which of the two tables has the duplicates -- or even if both do. So, you might need to do something similar for S.

SQL Join with SUM()

I have two Tables
Product Details(About Product)
Sale Order Details(What Price is sold, quantity of products sold per order).
I am trying to do Join on Table 1 and Table 2 which should give the all the product details and sum(Quantity), Sum(Price)
Problem Facing: There are some products in Table 1 which are never sold, and those rows are missing in the result set, but I want details for all the rows in Table 1 with rows of Products never purchased should be NULL or 'o'
Query I am Using:
select
P.*,
ISNULL((sum([Q.Quantity])),0),
ISNULL((sum([Q.Price])),0)
From Table1 P
Left Outer Join Table2 Q on P.Product_ID = Q.Product_ID
Please help me with any suggestions that would work for me
How about this one:
select
P.Product_ID,
ISNULL(sum([Q.Quantity]),0),
ISNULL(sum([Q.Price]),0)
From Table1 P
Left Outer Join Table2 Q
on P.Product_ID = Q.Product_ID
group by
P.Product_Id

Left Join returns more records

I have 2 tables with related data.
one table is for products. and the other price. In price table one product may appear several times.
How can I return the result showing the products without containing duplicate rows
My Query is
select p.Product, sum(p.Qty), max(pr.netprice)
from Products p
left outer join Price pr
on p.Product=pr.Product
where p.brand=''
group by p.Product,pr.Product
but return more rows as right table have multiple records
please help
I don't think distinct is the way to go, I think group by should result in what you want if done correctly. Also, I don't think you need to group on values from both tables.. You should really understand what you want to. Give us example data and it will be easier to answer your question. Try this:
select p.Product, sum(p.Qty), max(pr.netprice)
from Products p
left outer join Price pr on p.Product = pr.Product
where p.brand = ''
group by p.Product -- only group on param.
Use the distinct keyword. That will remove duplicates. ALthough, if there are different prices for a given product, there will be one record per unique price per product if you remove the Max().
select DISTINCT p.Product, sum(p.Qty),max(pr.netprice)
from Products p
left outer join Price pr on p.Product=pr.Product
where p.brand='' group by p.Product,pr.Product
Try putting distinct in select. I am not sure it will work, but try it.
If you want the sum then use Tomas answer above. This will give you a unique product list with the total quantity and maximum price for each product
select p.Product, sum(p.Qty), max(pr.netprice)
from Products p
left outer join Price pr on p.Product = pr.Product
where p.brand = ''
group by p.Product
What about changing it this way:
SELECT p.Product, sum(p.Qty),
(SELECT max(pr.netprice)
FROM Price pr
WHERE p.Product=pr.Product
)
FROM Products p
WHERE p.brand=''
Try this
SELECT p.Product, p.Qty, MAX(pr.netprice)
FROM Products p
LEFT OUTER JOIN Price pr ON p.Product=pr.Product
WHERE p.brand=''
GROUP BY p.Product, p.Qty