Answer:
with recentsales as
(select p.productid,
p.name as productname,
i.quantityavailable,
sum(od.quantity * p.price) as totalrevenue
from orderdetails od
join orders o on od.orderid = o.orderid
join products p on od.productid = p.productid
join inventory i on p.productid = i.productid
where o.orderdate::timestamp >= current_date - interval '30 days'
group by p.productid,
p.name,
i.quantityavailable)
select productid,
productname,
quantityavailable,
totalrevenue,
ntile(4) over (
order by totalrevenue desc) as demandtier
from recentsales;