/*分组后product_id= 2 有两组值,说明之前的group by product_id,unit_price,purchase_price 有两组不同的值,题目要求输出每个产品的总利润和利润率,即是忽略了unit_price,purchase_price的价格差异(实际生活中同一产品的进价和售价也不总是唯一的,是合理的),问题是我们要如何消除这种价格差异,容易想到用平均利润率来代指某商品总的利润率,而计算利润时sum(quantity) * (unit_price - purchase_price) 并没有消除价格带来的差异,只有sum(quantity*(unit_price - purchase_price)) 才能汇总利润;还有注意利润率的格式要求,是否保留百分号等......*/
select product_id
,sum(quantity * (unit_price - purchase_price)) as total_profit
,round(avg((unit_price - purchase_price) * 100 / purchase_price),2) as profit_margin
from sales_orders s
join purchase_prices p using(product_id)
where year(order_date) = 2023
group by product_id
order by product_id