I want to select only the latest membership_id from table user_payments of the user with the user_id equal to 1.
This is how the table user_payment looks like:
select * from
(SELECT MEMBSHIP_ID
FROM user_payment WHERE user_id=1
order by paym_date desc)
where rownum=1;
Oracle 9i+ (maybe 8i too) has FIRST/LAST aggregate functions, that make computation over groups of rows according to row's rank in group. Assuming all rows as one group, you'll get what you want without subqueries:
SELECT
max(MEMBSHIP_ID)
keep (
dense_rank first
order by paym_date desc NULLS LAST
) as LATEST_MEMBER_ID
FROM user_payment
WHERE user_id=1
SELECT p.MEMBSHIP_ID
FROM user_payments as p
WHERE USER_ID = 1 AND PAYM_DATE = (
SELECT MAX(p2.PAYM_DATE)
FROM user_payments as p2
WHERE p2.USER_ID = p.USER_ID
)
Try:
SELECT MEMBSHIP_ID
FROM user_payment
WHERE user_id=1
ORDER BY paym_date = (select MAX(paym_date) from user_payment and user_id=1);
Or:
SELECT MEMBSHIP_ID
FROM (
SELECT MEMBSHIP_ID, row_number() over (order by paym_date desc) rn
FROM user_payment
WHERE user_id=1 )
WHERE rn = 1
Try with:
select TO_CHAR(dates,'dd/MM/yyy hh24:mi') from ( SELECT min (TO_DATE(a.PAYM_DATE)) as dates from user_payment a )