Oracle,使用 order by desc 和 rownum 获取第一行
Oracle, get top row using order by desc and rownum
这个查询给出了无效标识符错误,我知道这是因为子查询将只能访问更高一层的数据。
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
);
现在,我在想是否有办法可以创建查询,在子查询中使用来自查询的数据时,只能 return 最新的行?
你可以试试这个:
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
您可以使用 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
这个查询给出了无效标识符错误,我知道这是因为子查询将只能访问更高一层的数据。
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
);
现在,我在想是否有办法可以创建查询,在子查询中使用来自查询的数据时,只能 return 最新的行?
你可以试试这个:
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
您可以使用 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