MAX(DATE) - SQL ORACLE

前端 未结 5 2109
感动是毒
感动是毒 2021-02-20 03:03

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:



        
相关标签:
5条回答
  • 2021-02-20 03:11
    select * from 
      (SELECT MEMBSHIP_ID
       FROM user_payment WHERE user_id=1
       order by paym_date desc) 
    where rownum=1;
    
    0 讨论(0)
  • 2021-02-20 03:12

    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
    
    0 讨论(0)
  • 2021-02-20 03:23
    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
    )
    
    0 讨论(0)
  • 2021-02-20 03:28

    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
    
    0 讨论(0)
  • 2021-02-20 03:34

    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 )
    
    0 讨论(0)
提交回复
热议问题