query SQL su rownum
Domanda
SELECT instmax
FROM
(SELECT instmax ,rownum r
FROM
( SELECT instmax FROM pswlinstmax ORDER BY instmax DESC NULLS LAST
)
WHERE r = 2
);
dopo l'esecuzione, sta dando questo errore:
ORA-00904: "R": invalid identifier
00904. 00000 - "%s: invalid identifier"
*Cause:
*Action:
Error at Line: 39 Column: 8
il motivo per cui sta dando questo errore ??
Soluzione
A causa alias non sono supportati nella clausola WHERE della stessa query. Così, invece scrivere il vostro domanda come:
SELECT instmax
FROM
(SELECT instmax ,rownum r
FROM
( SELECT instmax FROM pswlinstmax ORDER BY instmax DESC NULLS LAST
)
) WHERE r = 2;
Altri suggerimenti
Prima di tutto, non si può fare riferimento ad una seconda fila utilizzando una condizione rownum = 2
. È possibile selezionare prime due file specificando una condizione where rownum < 3
, o si può avvolgerlo in un'altra query e fare riferimento il vostro rownum
come una colonna normale da laggiù.
Quindi, non è possibile fare riferimento a un'alias di colonna in una clausola where
di una sottoquery è stato assegnato questo alias.
O si può portare ad un livello superiore:
SELECT instmax
FROM (SELECT instmax, rownum r
FROM (SELECT instmax
FROM pswlinstmax
ORDER BY instmax DESC NULLS LAST)
)
WHERE r = 2;
o semplicemente evitare questo riferimento
-- this will return first two rows
SELECT instmax
FROM (SELECT instmax, rownum r
FROM (SELECT instmax
FROM pswlinstmax
ORDER BY instmax DESC NULLS LAST)
WHERE rownum < 3
);
Non si può fare riferimento a un alias di colonna nella clausola WHERE del genere.
Il rownum non smettere di lavorare in questo modo sia. Provare qualcosa di simile:
select instmax from
(
SELECT instmax, row_number(instmax) order by (instmax desc nulls last) rownumber
FROM pswlinstmax
)
where rownumber = 2;
@Amit è giusto. Perché Oracle valuta prima la condizione WHERE, quindi selezionare. Devi fare sub-selezionate.
invece che:
SELECT instmax
FROM(
SELECT instmax ,rownum r
FROM (SELECT instmax FROM pswlinstmax ORDER BY instmax DESC NULLS LAST)
WHERE r = 2
);
effettuare le seguenti operazioni:
SELECT instmax
FROM ( SELECT instmax ,rownum r
FROM ( SELECT instmax FROM pswlinstmax ORDER BY instmax DESC NULLS LAST )
)
WHERE r = 2
;
... r è ora visibile alla clausola WHERE. Propably questa domanda è identicial / simile / duplicate per questo:
Un modo comune per ottenere diciamo cima cinque dipendenti ben pagati.
SELECT ename,sal FROM emp
WHERE rownum <= 5
ORDER BY sal DESC;