Oracle,使用desc和rownum命令获得最高行

时间:2016-10-26 07:21:51

标签: sql oracle greatest-n-per-group

此查询给出了无效的标识符错误,我知道这是因为子查询只能访问高一层的数据。

select *
from   t2_callerid_plan cp
where  cp.subsrefnum in (
       select *
       from   (
              select vsap.subsrefnum
              from   prv_internet_responses_vsap vsap
              where  vsap.subsrefnum = cp.subsrefnum
              order by vsap.id desc
       )
       where rownum = 1
);

现在,如果有方法我可以创建查询,在使用子查询中的查询数据时只能返回最新的行,我就会徘徊吗?

2 个答案:

答案 0 :(得分:2)

您可以使用ROW_NUMBER()

SELECT * FROM ( 
    SELECT cp.*,
           ROW_NUMBER() OVER(PARTITION BY cp.subsrefnum ORDER BY vsap.id desc) as rnk
    from t2_callerid_plan cp
    JOIN  prv_internet_responses_vsap vsap
     ON vsap.subsrefnum = cp.subsrefnum) p
WHERE p.rnk = 1

答案 1 :(得分:0)

你可以试试这个:

  select *
from   t2_callerid_plan cp
inner join
(
 select vsap.subsrefnum,ROW_NUMBER()  OVER (PARTITION BY subsrefnum ORDER BY vsap.id desc) rn
              from   prv_internet_responses_vsap vsap 
)vsap
on    vsap.subsrefnum = cp.subsrefnum and vsap.rn=1