HiveBrain v1.2.0
Get Started
← Back to all entries
snippetMinor

How to convert a Top 1 subquery using outer table alias to Oracle?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
topconvertsubqueryusinghoworaclealiastableouter

Problem

I have the following SQL Server query

select
    (select top 1 b2 from  BB b where b.b1 = a.a1 order by b2) calc,
    a1,
    a2
from AA a
where a2 = 2;


which I can rewrite using analytic functions

select
    (select b2 from 
    (select 
        row_number() over (order by b2) lfd, 
     b2 from  BB b where b.b1 = a.a1
    ) as t where lfd = 1
    ) calc,
    a1,
    a2
from AA a
where a2 = 2;


but when I convert this to oracle

create table AA ( a1 NUMBER(10), a2 NUMBER(10) );
insert into AA values ( 1, 1);
insert into AA values ( 1, 2);
insert into AA values ( 1, 3);
insert into AA values ( 2, 2);

create table BB ( b1 NUMBER(10), b2 NUMBER(10) );
insert into BB values ( 1, 1);
insert into BB values ( 2, 4);
insert into BB values ( 2, 5);

select * from AA;
select * from BB;

select
    (select b2 from 
    (select 
        row_number() over (order by b2) lfd, 
     b2 from  BB b where b.b1 = a.a1
    )  where lfd = 1
    ) calc,
    a1,
    a2
from AA a
where a2 = 2;


I get the following error

Error at line 5
ORA-00904: "A"."A1": invalid column name

Solution

you would perform the join first in Oracle:

SELECT a1, a2, b2
  FROM (SELECT a1, a2, b2, 
               row_number() over(PARTITION BY a.a1 ORDER BY b.b2) lfd
           FROM AA a
           LEFT JOIN BB b ON b.b1 = a.a1
          WHERE a2 = 2)
 WHERE lfd = 1


The problem with your query is that currently a subquery in Oracle can't access a value from a parent query more than two level deeper.

You could also use a PL/SQL function that would contain the inner SELECT.

Code Snippets

SELECT a1, a2, b2
  FROM (SELECT a1, a2, b2, 
               row_number() over(PARTITION BY a.a1 ORDER BY b.b2) lfd
           FROM AA a
           LEFT JOIN BB b ON b.b1 = a.a1
          WHERE a2 = 2)
 WHERE lfd = 1

Context

StackExchange Database Administrators Q#2013, answer score: 6

Revisions (0)

No revisions yet.