select s.product_id,
sum(s.unit_price*s.quantity)-p.purchase_price*sum(s.quantity) as total_profit,
round((avg(s.unit_price)-p.purchase_price)/p.purchase_price*100,2) as profit_margin
from sales_orders s join purchase_prices p on s.product_id=p.product_id
where year(s.order_date)=2023
group by p.product_id
order by p.product_id