¿Cómo puedo imprimir los primeros 2 valores máximos en una columna de base de datos usando SQL?

How can I print the first two maximum values under an attribute (column) in a database table using SQL?

Tengo una columna llamada salary that contains different rows, (approximately 10 rows). We need to print out the first two maximum values.

I know we can get the first maximum value by using max function, but what can I do if I need the first two values?

preguntado el 28 de agosto de 12 a las 09:08

SQL Server or MySQL, which is it? Make up your mind -

If you have like 1000, 1000, 900 in your table, then you need the 1000, 1000 as output or 1000 and 900. -

4 Respuestas

Perhaps something like this? (mysql)

select `salary` from `mytable` order by `salary` desc limit 2

As per Alex's answer, you can add the distinct keyword to ensure that you get two different values.

select distinct `salary` from `mytable` order by `salary` desc limit 2

Respondido 28 ago 12, 09:08

En SQL Server

SELECT TOP 2 salary
from table
order by salary desc

En MySQL

SELECT salary
from table
order by salary desc
limit 2

Respondido 28 ago 12, 09:08

select distinct salary from mytable order by salary desc limit 2;

Respondido 28 ago 12, 09:08

Ok If you need only the two top, even if the are equal, the others have rigth, but if you need the top 2 number (and you don't care if there are multiple instance from them) you can use this:

SELECT 
Salary 
FROM Salaries
GROUP BY Salary
ORDER BY Salary DESC
LIMIT 2

Respondido 28 ago 12, 09:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.