Consulta para encontrar el n-ésimo valor máximo de una columna
Quiero encontrar la 2ª,la 3ª..n-ésimo valor máximo de una columna
28 answers
Puede ordenar la columna en formato descendente y luego obtener el valor de la enésima fila.
EDITAR::
Actualizado según la solicitud de comentarios. AVISO ¡completamente sin probar!
SELECT DOB FROM (SELECT DOB FROM USERS ORDER BY DOB DESC) WHERE ROWID = 6
Algo como lo anterior debería funcionar para Oracle ... es posible que tenga que obtener la sintaxis correcta primero!
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
2011-09-19 13:15:29
Considere la siguiente tabla de empleados con una sola columna para el salario.
+------+ | Sal | +------+ | 3500 | | 2500 | | 2500 | | 5500 | | 7500 | +------+
La siguiente consulta devolverá el Enésimo elemento Maximum.
select SAL from EMPLOYEE E1 where
(N - 1) = (select count(distinct(SAL))
from EMPLOYEE E2
where E2.SAL > E1.SAL )
Por ejemplo. cuando se requiere el segundo valor máximo,
select SAL from EMPLOYEE E1 where
(2 - 1) = (select count(distinct(SAL))
from EMPLOYEE E2
where E2.SAL > E1.SAL )
+------+ | Sal | +------+ | 5500 | +------+
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
2009-04-15 06:39:38
No especificó qué base de datos, en MySQL puede hacer
SELECT column FROM table ORDER BY column DESC LIMIT 7,10;
Saltaría los primeros 7, y luego obtendría los siguientes diez más altos.
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
2008-09-17 07:22:20
De nuevo es posible que necesite arreglar su base de datos, pero si desea que el segundo valor superior en un conjunto de datos que potencialmente tenga el valor duplicado, también querrá hacer un grupo:
SELECT column
FROM table
WHERE column IS NOT NULL
GROUP BY column
ORDER BY column DESC
LIMIT 5 OFFSET 2;
Saltaría los dos primeros, y luego obtendría los cinco siguientes más altos.
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-10-26 15:44:19
SQL puro (nota: Yo recomendaría usar funciones SQL específicas para su DBMS ya que probablemente será más eficiente). Esto le dará el valor más grande n+1 (para obtener el más pequeño, voltee el
select id from table order by id desc limit 4 ;
+------+
| id |
+------+
| 2211 |
| 2210 |
| 2209 |
| 2208 |
+------+
SELECT yourvalue
FROM yourtable t1
WHERE EXISTS( SELECT COUNT(*)
FROM yourtable t2
WHERE t1.id <> t2.id
AND t1.yourvalue < t2.yourvalue
HAVING COUNT(*) = 3 )
+------+
| id |
+------+
| 2208 |
+------+
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
2008-09-17 12:32:09
(Nombre de la tabla=Estudiante, Nombre de la columna= marca)
select * from(select row_number() over (order by mark desc) as t,mark from student group by mark) as td where t=4
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
2012-11-20 05:34:55
Puede encontrar el enésimo valor más grande de la columna utilizando la siguiente consulta:
SELECT * FROM TableName a WHERE
n = (SELECT count(DISTINCT(b.ColumnName))
FROM TableName b WHERE a.ColumnName <=b.ColumnName);
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-06-04 07:59:27
Aquí hay un método para Oracle. Este ejemplo obtiene el 9º valor más alto. Simplemente reemplace el 9 con una variable bind que contenga la posición que está buscando.
select created from (
select created from (
select created from user_objects
order by created desc
)
where rownum <= 9
order by created asc
)
where rownum = 1
Si desea el enésimo valor único, agregaría DISTINCT en el bloque de consulta más interno.
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
2008-09-17 12:54:51
Select max(sal)
from table t1
where N (select max(sal)
from table t2
where t2.sal > t1.sal)
Para encontrar el Enésimo max sal.
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
2012-02-24 19:16:13
SELECT * FROM tablename
WHERE columnname<(select max(columnname) from tablename)
order by columnname desc limit 1
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
2012-06-03 11:31:58
Esta es la consulta para obtener la n-ésima más alta de colomn poner n=0 para el segundo más alto y n= 1 para el 3er más alto y así sucesivamente...
SELECT * FROM TableName
WHERE ColomnName<(select max(ColomnName) from TableName)-n order by ColomnName desc limit 1;
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
2014-11-28 11:24:50
select column_name from table_name
order by column_name desc limit n-1,1;
Donde n = 1, 2, 3,....n-ésimo valor máximo.
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-09-23 18:20:54
En SQL Server, simplemente haga:
select distinct top n+1 column from table order by column desc
Y luego deseche el primer valor, si no lo necesita.
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
2008-09-17 07:22:11
Para SQL 2005:
SELECT col1 from
(select col1, dense_rank(col1) over (order by col1 desc) ranking
from t1) subq where ranking between 2 and @n
Acabo de desenterrar esta pregunta al buscar la respuesta yo mismo, y esto parece funcionar para SQL Server 2005 (derivado de La solución de Blorgbeard):
SELECT MIN(q.col1) FROM (
SELECT
DISTINCT TOP n col1
FROM myTable
ORDER BY col1 DESC
) q;
Efectivamente, eso es un SELECT MIN(q.someCol) FROM someTable q
, con el n superior de la tabla recuperada por la consulta SELECT DISTINCT...
.
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-05-23 11:54:50
MySQL:
select distinct(salary) from employee order by salary desc limit (n-1), 1;
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
2012-01-28 10:23:12
Respuesta : segundo superior:
select * from (select * from deletetable where rownum <=2 order by rownum desc) where rownum <=1
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
2012-09-07 12:51:58
select sal,ename from emp e where
2=(select count(distinct sal) from emp where e.sal<=emp.sal) or
3=(select count(distinct sal) from emp where e.sal<=emp.sal) or
4=(select count(distinct sal) from emp where e.sal<=emp.sal) order by sal desc;
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
2012-09-21 20:38:03
Creo que la consulta a continuación funcionará perfectamente en oracle sql...Lo he probado yo mismo..
Información relacionada con esta consulta: esta consulta está utilizando dos tablas llamadas employee
y department
con columnas en empleado llamado: name
(nombre del empleado), dept_id
(común a empleado y departamento), salary
Y columnas en la tabla del departamento: dept_id
(común para la tabla del empleado también), dept_name
SELECT
tab.dept_name,MIN(tab.salary) AS Second_Max_Sal FROM (
SELECT e.name, e.salary, d.dept_name, dense_rank() over (partition BY d.dept_name ORDER BY e.salary) AS rank FROM department d JOIN employee e USING (dept_id) ) tab
WHERE
rank BETWEEN 1 AND 2
GROUP BY
tab.dept_name
Gracias
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-07-26 07:37:55
Otro para Oracle usando funciones analíticas:
select distinct col1 --distinct is required to remove matching value of column
from
( select col1, dense_rank() over (order by col1 desc) rnk
from tbl
)
where rnk = :b1
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-08-02 19:57:06
Select min(fee)
from fl_FLFee
where fee in (Select top 4 Fee from fl_FLFee order by 1 desc)
Cambie el número cuatro por N.
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-17 09:56:03
Puedes simplificar así
SELECT MIN(Sal) FROM TableName
WHERE Sal IN
(SELECT TOP 4 Sal FROM TableName ORDER BY Sal DESC)
Si el Sal contiene valores duplicados, use este
SELECT MIN(Sal) FROM TableName
WHERE Sal IN
(SELECT distinct TOP 4 Sal FROM TableName ORDER BY Sal DESC)
El 4 será el n-ésimo valor que puede cualquier valor más alto, como 5 o 6, etc.
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
2014-07-17 11:04:52
(TableName = Student, ColumnName = Mark):
select *
from student
where mark=(select mark
from(select row_number() over (order by mark desc) as t,
mark
from student group by mark) as td
where t=2)
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-09-05 22:08:05
Consulta SQL simple para obtener el detalle del empleado que tiene Nth MAX Salary
en la tabla Employee
.
sql> select * from Employee order by salary desc LIMIT 1 OFFSET <N - 1>;
Considere la estructura de la tabla como:
Empleado ( id [int primary key auto_increment], nombre [varchar(30)], salario [int]);
Ejemplo:
Si necesita 3rd MAX
salario en la tabla anterior, entonces, la consulta será:
sql> select * from Employee order by salary desc LIMIT 1 OFFSET 2;
Del mismo modo:
Si necesita 8th MAX
salario en la tabla anterior entonces, consulta será:
sql> select * from Employee order by salary desc LIMIT 1 OFFSET 7;
NOTA: Cuando usted tiene que conseguir el Nth
MAX
valor debe dar elOFFSET
como (N - 1).
Así se puede hacer el mismo tipo de operación en caso de salario en orden ascendente.
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-09-20 13:00:21
En PostgreSQL, para encontrar el N-ésimo salario más grande de la tabla de empleados.
SELECT * FROM Employee WHERE salary in
(SELECT salary FROM Employee ORDER BY salary DESC LIMIT N)
ORDER BY salary ASC LIMIT 1;
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-01-01 21:20:40
Mysql query: supongamos que quiero averiguar enésima tabla de empleados del formulario de salario máximo
select salary
form employee
order by salary desc
limit n-1,1 ;
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-08-07 10:00:11
Solución para encontrar el N-ésimo valor máximo de una columna en particular en SQL Server:
Tabla de empleados:
Tabla de ventas:
Datos de la tabla de empleados:
==========
Id name
=========
6 ARSHAD M
7 Manu
8 Shaji
Datos de la tabla de ventas:
=================
id emp_id amount
=================
1 6 500
2 7 100
3 8 100
4 6 150
5 7 130
6 7 130
7 7 330
Consulta para Averiguar los detalles de un empleado que tiene la venta más alta/ Nth vendedor más alto
select * from (select E.Id,E.name,SUM(S.amount) AS 'total_amount' from employee E INNER JOIN Sale S on E.Id=S.emp_id group by S.emp_id,E.Id,E.name ) AS T1 WHERE(0)=( select COUNT(DISTINCT(total_amount)) from(select E.Id,E.name,SUM(S.amount) AS 'total_amount' from employee E INNER JOIN Sale S on E.Id=S.emp_id group by S.emp_id,E.Id,E.name )AS T2 WHERE(T1.total_amount<T2.total_amount) );
En el DONDE (0) sustitúyase 0 por n-1
Resultado:
========================
id name total_amount
========================
7 Manu 690
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-10-01 18:17:56
Tabla empleado
salary
1256
1256
2563
8546
5645
Se encuentra el segundo valor máximo mediante esta consulta
select salary
from employee
where salary=(select max(salary)
from employee
where salary <(select max(salary) from employee));
Se encuentra el tercer valor máximo mediante esta consulta
select salary
from employee
where salary=(select max(salary)
from employee
where salary <(select max(salary)
from employee
where salary <(select max(salary)from employee)));
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
2012-09-29 11:43:59