简体   繁体   中英

Sort Products based on the latest Order that referenced it - PostgreSQL

I need to show a list of products sorted by the latest orders that had this product in its composition.
An image for reference:

在此处输入图像描述

And then you'd have Product 2 with it's corresponding orders sorted by the order's creation date. So, I'll have to group the orders based on the presence of a product, then order these groups based on the latest order within it. This will be used to show the "most recent ordered products" but I have no idea on how to write the query without bloated super expensive methods.
Could someone provide any references please?

Assume that you have two tables as below: Products (productid, Name etc..) Orders (orderid, order_date, product_id etc..)

Then you first need to sort the orders for a particular product by order_date. I have used CTE with row_number() function to achieve that then have selected only the first order information order by order_date in descending order.

with order_product as (
select o.orderid,o.order_date,o.product_id,p.name,row_number()over(partition by o.product_id order by order_date desc)rn
 from orders o inner join products p on o.productid=p.productid
) select * from order_product where rn=1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM