Search code examples
sqloraclegreatest-n-per-group

Filtering rows to get only the latest value


I have the following data in a table:

ORDERID, PRODUCT,  QUANTITY
1,       potatoes, 10
1,       oranges,  20
2,       apples,   10
2,       oranges,  15
3,       pears,    20
3,       peaches,  12

I would like to query the table to filter out repeated products (e.g. oranges), taking only the latest (higher ORDERID) value. This should then result in:

ORDERID, PRODUCT,  QUANTITY
1,       potatoes, 10
2,       apples,   10
2,       oranges,  15
3,       pears,    20
3,       peaches,  12

Solution

  • select  *
    
    from   (select      t.*
                       ,row_number () over (partition by PRODUCT order by ORDERID desc) as rn
    
            from        mytable t
            )
    
    where   rn = 1