11

我只想从 user_id 等于 1 的用户的 user_payments 表中选择最新的 members_id。

这是表 user_payment 的样子:

   PAYM_ID    USER_ID MEMBSHIP_ID PAYM_DATE                     
---------- ---------- ----------- -------------------------------
         1          1           1 18-DEC-09 12.00.00.000000000 AM 
         2          1           2 18-DEC-10 12.00.00.000000000 AM 
         3          1           2 18-DEC-11 12.00.00.000000000 AM 
         4          2           3 17-MAR-11 12.00.00.000000000 AM 
         5          3           3 18-JUN-12 12.00.00.000000000 AM 
         6          4           2 17-FEB-12 12.00.00.000000000 AM 
         7          5           2 18-FEB-11 12.00.00.000000000 AM 
         8          5           2 18-FEB-12 12.00.00.000000000 AM 
         9          6           1 01-JUN-12 12.00.00.000000000 AM 
        10          7           1 03-FEB-11 12.00.00.000000000 AM 
        11          7           2 03-FEB-12 12.00.00.000000000 AM 

我正在尝试以下代码但没有成功:

SELECT MEMBSHIP_ID
FROM user_payment
WHERE user_id=1 and MAX(paym_date);

我收到此错误: SQL 错误:ORA-00934:此处不允许使用组功能 00934。00000 -“此处不允许使用组功能”

我该如何解决?提前致谢!

4

5 回答 5

22
select * from 
  (SELECT MEMBSHIP_ID
   FROM user_payment WHERE user_id=1
   order by paym_date desc) 
where rownum=1;
于 2012-07-09T07:52:59.833 回答
12
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
)
于 2012-07-09T07:38:32.630 回答
3

尝试:

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);

或者:

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
于 2012-07-09T07:49:43.487 回答
0

Oracle 9i+(也可能是 8i)具有 FIRST/LAST 聚合函数,可以根据行在组中的排名对行组进行计算。假设所有行为一组,您将获得所需的内容,而无需子查询:

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
于 2013-05-14T00:00:40.243 回答
-1

尝试:

select TO_CHAR(dates,'dd/MM/yyy hh24:mi') from (  SELECT min  (TO_DATE(a.PAYM_DATE)) as dates from user_payment a )
于 2016-12-07T09:16:01.407 回答