I have 2 tables, one is a recipe_tbl, and second is prepared_tbl as follow:
recipe_tbl
Product_ID
Product_Name
Req_Qty
Units
F-0001
Flour
120
gr
S-0001
Sugar
100
gr
prepared_tbl
Trans_Code
Trans_Date
Product_ID
Qty
Units
t-2302-001
2023-02-16
F-0001
10
gr
t-2302-002
2023-02-16
F-0001
10
gr
t-2302-003
2023-02-16
S-0001
10
gr
What I want is to generate sum as follow:
Product_ID
Product_Name
Req_Qty
Units
Prepared
Remaining
F-0001
Flour
120
gr
20
100
S-0001
Sugar
100
gr
10
90
How to do that in query?
This is my query, but it doesn't work :
select a.Product_ID , sum(b.Qty)
from recipe_tbl a
left join prepared_tbl b
on b.Product_ID = a.Product_ID
group by a.Product_ID
Please help we with the correct query, thank you in advance!
select a.Product_ID , sum(b.Qty)
from recipe_tbl a
left join prepared_tbl b
on b.Product_ID = a.Product_ID
group by a.Product_ID
You can use the following SQL query to generate the results you're looking for:
SELECT
r.Product_ID,
r.Product_Name,
r.Req_Qty,
r.Units,
SUM(p.Qty) AS Prepared,
r.Req_Qty - SUM(p.Qty) AS Remaining
FROM recipe_tbl r
LEFT JOIN prepared_tbl p ON r.Product_ID = p.Product_ID
GROUP BY r.Product_ID, r.Product_Name, r.Req_Qty, r.Units;
To be in the safe side, when there are no matching rows in the 'prepared_tbl' use COALESCE to return 0. Check below query with COALESCE function:
SELECT
r.Product_ID,
r.Product_Name,
r.Req_Qty,
r.Units,
COALESCE(SUM(p.Qty), 0) AS Prepared,
r.Req_Qty - COALESCE(SUM(p.Qty), 0) AS Remaining
FROM recipe_tbl r
LEFT JOIN prepared_tbl p ON r.Product_ID = p.Product_ID
GROUP BY r.Product_ID, r.Product_Name, r.Req_Qty, r.Units;
Related
I have 3 tables, a purchase (p), a refund (r) and a send to finance software batching table (b).
Set up like this:
purchases
=========
order_number VARHCAR(10)
order_id (number)
order_date (date)
refunds
=======
refund_id (number)
order_id <-- relates to purchases table (number)
refund_date (date)
send_to_finance_batch
=====================
generic_id (number) <-- this can be filled in by an number of tables
type (text)
status_reason (text)
satus_id (number)
(more or less)
What I need to figure out is how to do a left join (since the generic_id can come from several entities) refunds to purchases?
Right now I have this:
SELECT p.order_number,
b.generic_id,
b.status_id,
b.status_reason,
FROM send_to_finance_batching b
LEFT JOIN purchases p ON b.generic_id = p.order_id
WHERE...
refund_id OR order_id will equal the generic_id so I need to relate generic_id to refund_id and then from the refunds table order_id to orders table.
My desired output is to be able to fill in p.order_number, right now I have the other columns but since order_number only exists on the purchase table id like to link it back to the refunds table by joining on the batching table.
What I have right now is this:
Order number | type | generic_id | status_reason | status_id
==============================================================
| refund | 1234567890 | 'stuck' | 99
WH763HWW3499 | purch | 7534567654 | 'error' | 99
I would like to be able to fill in the order number on the refunds, but since generic_id relates to the refund_id I need to be able to use the order_id from refunds to get the info from purchases and have a complete query
Option 1: Using UNION
In this case you would lose rows that neither can be joined to purchases nor refunds.
SELECT p.order_number,
b.generic_id,
b.status_id,
b.status_reason
FROM send_to_finance_batching b
JOIN purchases p ON b.generic_id = p.order_id
WHERE...
UNION
SELECT p.order_number,
b.generic_id,
b.status_id,
b.status_reason
FROM send_to_finance_batching b
JOIN refunds r ON b.generic_id = r.refund_id
JOIN purchases p ON r.order_id = p.order_id
WHERE...
Option 2: JOIN purchases multiple times and using COALESCE
SELECT coalesce(p.order_number, p2.order_number) order_number,
b.generic_id,
b.status_id,
b.status_reason
FROM send_to_finance_batching b
LEFT JOIN purchases p ON b.generic_id = p.order_id
LEFT JOIN refunds r ON b.generic_id = r.refund_id
LEFT JOIN purchases p2 ON r.order_id = p2.order_id
WHERE...
Option 3: Use COALESCE on JOIN condition
SELECT p.order_number,
b.generic_id,
b.status_id,
b.status_reason
FROM send_to_finance_batching b
LEFT JOIN refunds r ON b.generic_id = r.refund_id
LEFT JOIN purchases p ON coalesce(r.order_id, b.generic_id) = p.order_id
WHERE...
Outer join the two tables, but consider the type column in order not to join the wrong entity. Then use COALESCE to display the order number from the referenced row.
SELECT
COALESCE(p.order_id, r.order_id) AS order_id,
fb.generic_id,
fb.status_id,
fb.status_reason
FROM send_to_finance_batching fb
LEFT JOIN purchases p ON fb.generic_id = p.order_id AND fb.type = 'purch'
LEFT JOIN refunds r ON fb.generic_id = r.refund_id AND fb.type = 'refund'
ORDER BY order_id;
I have problems with some query. I need to get max value and product_name from that query:
select
products.product_name,
sum(product_invoice.product_amount) as total_amount
from
product_invoice
inner join
products on product_invoice.product_id = products.product_id
inner join
invoices on product_invoice.invoice_id = invoices.invoice_id
where
month(invoices.invoice_date) = 2
group by
products.product_name
This query returns a result like this:
product_name | total_amount
--------------+--------------
chairs | 70
ladders | 500
tables | 150
How to get from this: ladders 500?
Select product_name,max(total_amount) from(
select
products.product_name,
sum(product_invoice.product_amount) as total_amount
from product_invoice
inner join products
on product_invoice.product_id = products.product_id
inner join invoices
on product_invoice.invoice_id = invoices.invoice_id
where month(invoices.invoice_date) = 2
group by products.product_name
) outputTable
You can use order by and fetch first 1 row only:
select p.product_name,
sum(pi.product_amount) as total_amount
from product_invoice pi inner join
products p
on pi.product_id = p.product_id inner join
invoices i
on pi.invoice_id = i.invoice_id
where month(i.invoice_date) = 2 -- shouldn't you have the year here too?
group by p.product_name
order by total_amount
fetch first 1 row only;
Not all databases support the ANSI-standard fetch first clause. You may need to use limit, select top, or some other construct.
Note that I have also introduced table aliases -- they make the query easier to write and to read. Also, if you are selecting the month, shouldn't you also be selecting the year?
In older versions of SQL Server, you would use select top 1:
select top (1) p.product_name,
sum(pi.product_amount) as total_amount
from product_invoice pi inner join
products p
on pi.product_id = p.product_id inner join
invoices i
on pi.invoice_id = i.invoice_id
where month(i.invoice_date) = 2 -- shouldn't you have the year here too?
group by p.product_name
order by total_amount;
To get all rows with the top amount, use SELECT TOP (1) WITH TIES . . ..
If you are using SQL Server, then TOP can offer a solution:
SELECT TOP 1
p.product_name,
SUM(pi.product_amount) AS total_amount
FROM product_invoice pi
INNER JOIN products p
ON pi.product_id = p.product_id
INNER JOIN invoices i
ON pi.invoice_id = i.invoice_id
WHERE
MONTH(i.invoice_date) = 2
GROUP BY
p.product_name
ORDER BY
SUM(pi.product_amount) DESC;
Note: If there could be more than one product tied for the top amount, and you want all ties, then use TOP 1 WITH TIES, e.g.
SELECT TOP 1 WITH TIES
... (the same query I have above)
I need some help I have 3 tables
http://i.stack.imgur.com/TB3MX.jpg
My code:
select nazev_produkt,
SUM(mnozstvi_objednavka_dod)'bylo na sklade'
from Produkty p join Objednavky_dodavatele od on
p.id_produkt=od.id_produkt
where stavzbozi_objednavka_dod=('na skladě')
group by nazev_produkt
select nazev_produkt,SUM(mnozstvi_objednavka_zak)koupili
from Objednavky_zakaznici oz join Produkty p
on oz.id_produkt=p.id_produkt
where stav_objednavka_zak=('dodané')
group by nazev_produkt
I want to create select code from both of this selected which will consist of nazev_produkt, 'bylo na sklade - koupili' and group by nazev_produkt
basically
bylo na sklade = was in stock
koupili = purchased.
I need to deduct the purchased - was in stock and show nazev_produkt (Product Name), na sklade (In Stock)
Help is much appreciated!
I can't read your language, so making a few guesses here... :-) The table joining, I think, answers your question in any case.
select
p.product_name,
--isnull(i.quantity,0) as was_in_stock,
--isnull(s.quantity,0) as sold,
isnull(i.quantity,0) - isnull(s.quantity,0) as [currently_in_stock]
from
products p
LEFT JOIN (select product_id, sum(quantity) as quantity from inventory group by product_id) i
ON p.product_id = i.product_id
LEFT JOIN (select product_id, sum(quantity) as quantity from sales group by product_id) s
ON p.product_id = s.product_id
group by
product_name
Add a third column with the typization of your source.
Try this:
select nazev_produkt,
isnull(
(select SUM(mnozstvi_objednavka_dod)
from Objednavky_dodavatele od
where p.id_produkt=od.id_produkt),
0) -
isnull(
(select SUM(mnozstvi_objednavka_zak)
from Objednavky_zakaznici oz
where oz.id_produkt=p.id_produkt),
0)
from Produkty p
where stavzbozi_objednavka_dod=('na sklade')
or stav_objednavka_zak=('dodané')
If it helps, I'm using Opencart shopping cart & I am after showing an extra column in the reports-products-purchased page.
I can get it to display the quantity of items per category & also the total costs using the following code...
SELECT COUNT( DISTINCT op.model ) AS quantity, SUM( op.total + op.total * op.tax /100 ) AS total
FROM `order_product` op
LEFT JOIN `product_to_category` ptc
ON ( op.product_id = ptc.product_id )
WHERE ptc.category_id =192
OR ptc.category_id =177
GROUP BY category_id
this will display 7 items from a certain category totalling 135.00 & 5 items from the other category totalling 105.00
Quantity Total
7 135.00
5 105.00
But I am after displaying the name of the category from another table called category so that it displays like this
Category Quantity Total
Womens 7 135.00
Mens 5 105.00
I have tried linking the *product_to_category* to the category using LEFT JOIN, but i'm only a novice at this so any help would be great ;)
you just need to join on the category table and add your name.
SELECT c.name
, COUNT( DISTINCT op.model ) AS quantity
, SUM( op.total + op.total * op.tax /100 ) AS total
FROM order_product op
LEFT JOIN product_to_category ptc
ON op.product_id = ptc.product_id
LEFT JOIN category_description c
on ptc.category_id = c.category_id
WHERE ptc.category_id =192
OR ptc.category_id =177
GROUP BY ptc.category_id, c.name
Since you new to JOINs here is a helpful explanation of joins
A Visual Explanation of SQL Joins
Add the category description (whatever it's name is) to the select and the group by. You do not need the product_id in the group by if it is not included in the select.
SELECT ptc.CategoryDescription, COUNT( DISTINCT op.model ) AS quantity,
SUM( (op.total+op.total) * op.tax/100 ) AS total
FROM order_product op
LEFT JOIN product_to_category ptc ON ( op.product_id = ptc.product_id )
WHERE ptc.category_id =192
OR ptc.category_id =177
GROUP BY ptc.CategoryDesription
I have three tables:
CustOrder: id, CreateDate, Status
DenominationOrder: id, DenID, OrderID
Denomination: id, amount
I want to create a view based upon all these tables but there should be an additional column i.e. Total should be there which can calculate the sum of the amount of each order.
e.g.
order 1 total denominations 3, total amount = 250+250+250=750
order 2 total denominations 2, total amount = 250+250=500
Is it possible?
I try to guess your table relations (and data too, you did not provide any sample):
SELECT co.id,
COUNT(do.DenID) AS `Total denominations`,
SUM(d.amount) AS `Total amount`
FROM CustOrder co
INNER JOIN DenominationOrder do ON co.id = do.OrderId
INNER JOIN Denomination d ON do.DenId = d.id
GROUP BY co.id
Try this:
SELECT o.CreateDate, COUNT(o.id), SUM(d.amount) AS 'Total Amount'
FROM CustOrder o
INNER JOIN DenominationOrder do ON o.id = do.OrderID
INNER JOIN Denomination d ON do.DenId = d.id
GROUP BY o.CreateDate
DEMO
Another way to do this, by using CTE, like this:
;WITH CustomersTotalOrders
AS
(
SELECT o.id, SUM(d.amount) AS 'TotalAmount'
FROM CustOrder o
INNER JOIN DenominationOrder do ON o.id = do.OrderID
INNER JOIN Denomination d ON do.DenId = d.id
GROUP BY o.id
)
SELECT o.id, COUNT(ot.id) AS 'Orders Count', ot.TotalAmount
FROM CustOrder o
INNER JOIN CustomersTotalOrders ot on o.id = ot.id
INNER JOIN DenominationOrder do ON ot.id = do.OrderID
INNER JOIN Denomination d ON do.DenId = d.id
GROUP BY o.id, ot.TotalAmount
This will give you:
id | Orders Count | Total Amount
-------+---------------+-------------
1 3 750
2 2 500
DEMO using CTE