What is the simplest SQL Query to find the second

2019-01-02 14:44发布

What is the simplest SQL query to find the second largest integer value in a specific column?

There are maybe duplicate values in the column.

标签: sql puzzle
30条回答
不流泪的眼
2楼-- · 2019-01-02 14:48

Simplest of all

select sal from salary order by sal desc limit 1 offset 1
查看更多
明月照影归
3楼-- · 2019-01-02 14:50

Old question I know, but this gave me a better exec plan:

 SELECT TOP 1 LEAD(MAX (column)) OVER (ORDER BY column desc)
 FROM TABLE 
 GROUP BY column
查看更多
余生请多指教
4楼-- · 2019-01-02 14:50

It is the most esiest way:

SELECT
      Column name
FROM
      Table name 
ORDER BY 
      Column name DESC
LIMIT 1,1
查看更多
若你有天会懂
5楼-- · 2019-01-02 14:50

As you mentioned duplicate values . In such case you may use DISTINCT and GROUP BY to find out second highest value

Here is a table

salary

:

enter image description here

GROUP BY

SELECT  amount FROM  salary 
GROUP by amount
ORDER BY  amount DESC 
LIMIT 1 , 1

DISTINCT

SELECT DISTINCT amount
FROM  salary 
ORDER BY  amount DESC 
LIMIT 1 , 1

First portion of LIMIT = starting index

Second portion of LIMIT = how many value

查看更多
妖精总统
6楼-- · 2019-01-02 14:51

Query to find the 2nd highest number in a row-

select Top 1 (salary) from XYZ
where Salary not in (select distinct TOP 1(salary) from XYZ order by Salary desc)
ORDER BY Salary DESC

By changing the highlighted Top 1 to TOP 2, 3 or 4 u can find the 3rd, 4th and 5th highest respectively.

查看更多
长期被迫恋爱
7楼-- · 2019-01-02 14:52
SELECT 
    * 
FROM 
    table 
WHERE 
    column < (SELECT max(columnq) FROM table) 
ORDER BY 
    column DESC LIMIT 1
查看更多
登录 后发表回答