I have a question regarding the use of UNION ALL and INNER JOIN. I found some posts regarding this issue, for example here or there but I did not manage to apply it to my issue. What I am trying to do is to list 1) the products and 2) the difference between orders and deliveries. I have 3 table:
I managed to get (almost) what I want using the following:
SELECT product
, sum(total)
FROM (
SELECT product
, SUM(value) as total
FROM orders
GROUP BY product
union all
SELECT product
, -1 * SUM(value) as total
FROM deliveries
GROUP BY product)
as alias
GROUP BY product
ORDER BY sum(total) DESC
I obtain the following:
When I would like to get:
Meaning the product name instead of the product id. Anyone would have a solution for that? (my INNER JOIN OR LEFT JOIN attempts failed so far) Thanks and regards
Join in the product table:
SELECT p.name, sum(total)
FROM (SELECT o.product, SUM(o.value) as total
FROM orders o
GROUP BY o.product
union all
SELECT d.product, -1 * SUM(d.value) as total
FROM deliveries d GROUP BY d.product
) od JOIN
product p
on od.product = p.id
GROUP BY p.name
ORDER BY sum(total) DESC
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.