¿Cómo hago el top 1 en Oracle?


¿Cómo hago lo siguiente?

select top 1 Fname from MyTbl

In Oracle 11g?

Author: a_horse_with_no_name, 2010-08-10

9 answers

Si desea solo una primera fila seleccionada, puede:

select fname from MyTbl where rownum = 1

También puede usar funciones analíticas para ordenar y tomar la x superior:

select max(fname) over (rank() order by some_factor) from MyTbl
 209
Author: mcpeterson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-12 14:36:12
SELECT *
  FROM (SELECT * FROM MyTbl ORDER BY Fname )
 WHERE ROWNUM = 1;
 133
Author: Damian Leszczyński - Vash,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-10 17:13:26

Con Oracle 12c (junio de 2013), puede usarlo de la siguiente manera.

SELECT * FROM   MYTABLE
--ORDER BY COLUMNNAME -OPTIONAL          
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
 22
Author: MSK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-12 14:38:15

Podría usar ROW_NUMBER() con una cláusula ORDER BY en la sub-consulta y usar esta columna en reemplazo de TOP N. Esto se puede explicar paso a paso.

Véase el cuadro siguiente, que tiene dos columnas NAME y DT_CREATED.

introduzca la descripción de la imagen aquí

Si necesita tomar solo las dos primeras fechas independientemente de NAME, puede usar la siguiente consulta. La lógica ha sido escrita dentro de query

-- The number of records can be specified in WHERE clause
SELECT RNO,NAME,DT_CREATED
FROM
(
    -- Generates numbers in a column in sequence in the order of date
    SELECT ROW_NUMBER() OVER (ORDER BY DT_CREATED) AS RNO,
    NAME,DT_CREATED
    FROM DEMOTOP
)TAB
WHERE RNO<3;

RESULTADO

introduzca la descripción de la imagen aquí

En algunos situaciones, tenemos que seleccionar TOP N resultados respectivos a cada NAME. En tal caso podemos usar PARTITION BY con una cláusula ORDER BY en la sub-consulta. Consulte la siguiente consulta.

-- The number of records can be specified in WHERE clause
SELECT RNO,NAME,DT_CREATED
FROM
(
  --Generates numbers in a column in sequence in the order of date for each NAME
    SELECT ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY DT_CREATED) AS RNO,
    NAME,DT_CREATED
    FROM DEMOTOP
)TAB
WHERE RNO<3;

RESULTADO

introduzca la descripción de la imagen aquí

 9
Author: Sarath Avanavu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-06 04:59:01

, puedes hacer algo como

    SELECT *
      FROM (SELECT Fname FROM MyTbl ORDER BY Fname )
 WHERE rownum = 1;

También podría usar las funciones analíticas RANK y/o DENSE_RANK, pero ROWNUM es probablemente la más fácil.

 7
Author: Suman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-10 05:20:39

Uso:

SELECT x.*
  FROM (SELECT fname 
          FROM MyTbl) x
 WHERE ROWNUM = 1

Si usas Oracle9i+, podrías mirar usando funciones analíticas como ROW_NUMBER() pero no funcionarán tan bien como ROWNUM.

 5
Author: OMG Ponies,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-10 17:31:21
select * from (
    select FName from MyTbl
)
where rownum <= 1;
 5
Author: a'r,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-06 10:07:00

Para seleccionar la primera fila de una tabla y para seleccionar una fila de una tabla son dos tareas diferentes y necesitan una consulta diferente. Hay muchas maneras posibles de hacerlo. Cuatro de ellos son:

Primero

select  max(Fname) from MyTbl;

Segundo

select  min(Fname) from MyTbl;

Tercero

select  Fname from MyTbl  where rownum = 1;

Cuarto

select  max(Fname) from MyTbl where rowid=(select  max(rowid) from MyTbl)
 3
Author: Vikas Hardia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-12 14:37:37

Tuve el mismo problema, y puedo arreglar esto con esta solución:

select a.*, rownum 
from (select Fname from MyTbl order by Fname DESC) a
where
rownum = 1

Puede ordenar su resultado antes de tener el primer valor en la parte superior.

Buena suerte

 2
Author: user2607028,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-21 17:17:54