'postgres combining two queries from the result between them
I Have two postgres query. This is the first query
SELECT line.quantity, inv.origin, spo.lot_id
FROM account_invoice inv
INNER JOIN account_invoice_line line on inv.id=line.invoice_id
LEFT JOIN stock_picking pick on inv.origin=pick.name
LEFT JOIN stock_pack_operation spo ON pick.id=spo.picking_id
WHERE line.product_id=4988
AND pick.min_date between '2021-02-20' and '2021-03-22';
with result
quantity | origin | lot_id
----------+---------------+--------
25.00 | SNL/OUT/02317 | 6528
25.00 | SNL/OUT/02306 | 6774
150.00 | SNL/OUT/02337 | 6774
And the second query is
SELECT spo.product_qty, spo.lot_id
FROM stock_pack_operation spo
LEFT JOIN stock_picking sp ON sp.id=spo.picking_id
WHERE sp.origin='PO/2021/1/2307';
with the result of second query:
product_qty | lot_id
-------------+--------
200.00 | 6774
200.00 | 6852
The question is what is the query to have result like this
quantity | origin | lot_id
----------+---------------+--------
25.00 | SNL/OUT/02306 | 6774
150.00 | SNL/OUT/02337 | 6774
Thank you for the help
Solution 1:[1]
Finally, I got the answer. It use IN
SELECT line.quantity, inv.origin, spo.lot_id
FROM account_invoice inv
INNER JOIN account_invoice_line line on inv.id=line.invoice_id
LEFT JOIN stock_picking pick on inv.origin=pick.name
LEFT JOIN stock_pack_operation spo ON pick.id=spo.picking_id
WHERE line.product_id=4988
AND pick.min_date between '2021-02-20' and '2021-03-22'
AND spo.lot_id IN
(SELECT spo2.lot_id
FROM stock_pack_operation spo2
LEFT JOIN stock_picking sp2 ON sp2.id=spo2.picking_id
WHERE sp2.origin='PO/2021/1/2307');
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kai - Kazuya Ito |
