select s.product_id,sum(quantity * unit_price)-sum(quantity * purchase_price) total_profit
,round((avg(unit_price) / purchase_price -1) * 100, 2) profit_margin
from sales_orders s join purchase_prices using (product_id)
group by s.product_id
order by s.product_id