with details as (
    select p.product_id
    ,product_name
    ,category_id
    ,sales_amount
    ,cost_amount
    ,row_number() over(partition by category_id order by    sales_amount desc) as rk
from sales_and_profit s 
join product_category p on s.product_id = p.product_id
)

select product_id
,product_name
,category_id
,sales_amount
,round((sales_amount - cost_amount) / sales_amount,2) as profit_rate
from details
where round((sales_amount - cost_amount) / sales_amount,2) > 0.20
and rk <= 3
group by product_id
,product_name
,category_id
,sales_amount
,profit_rate
order by category_id
,sales_amount desc
,product_id