In the example below, the subquery actually returns a temporary table which is handled by database server in memory.
The temporary table from the subquery is given an alias so that we can refer to it in the outer select statement.
Note that the left and right table of the join keyword must both return a common key that can be used for the join.
Also note that, using subquery in JOIN operation should generally be avoided if you can rewrite your query
in a different way, the reason being that no indexes can be used on a temporary table in memory.
select y.CategoryID,
y.CategoryName,
round(x.actual_unit_price, 2) as "Actual Avg Unit Price",
round(y.planned_unit_price, 2) as "Would-Like Avg Unit Price"
from
(
select avg(a.UnitPrice) as actual_unit_price, c.CategoryID
from order_details as a
inner join products as b on b.ProductID = a.ProductID
inner join categories as c on b.CategoryID = c.CategoryID
group by c.CategoryID
) as x
inner join
(
select a.CategoryID, b.CategoryName, avg(a.UnitPrice) as planned_unit_price
from products as a
inner join categories as b on b.CategoryID = a.CategoryID
group by a.CategoryID
) as y on x.CategoryID = y.CategoryID