One option is to use analytic function (such as row_number
or rank
) to "sort" data; then extract rows that rank as the highest:
Sample data:
SQL> with purchase_Details (purchase_id, product_id, purchase_price, sale_price) as
2 (select 3, 1, 15000, 16000 from dual union all
3 select 4, 1, 13000, 14000 from dual union all
4 select 3, 4, 500, 700 from dual union all
5 select 2, 4, 400, 500 from dual
6 ),
Query begins here:
7 temp as
8 (select p.*,
9 row_number() over (partition by product_id order by purchase_id desc) rn
10 from purchase_details p
11 )
12 select purchase_id, product_id, purchase_price, sale_price
13 from temp
14 where rn = 1;
PURCHASE_ID PRODUCT_ID PURCHASE_PRICE SALE_PRICE
----------- ---------- -------------- ----------
4 1 13000 14000
3 4 500 700
SQL>