取得表格中的第二高价值


14
id value
1   50
2   60
3   55

select max(value) from tablename;

通常我们知道,我们将得到60,但是我需要下一个值55。

如何使用SQL获取值55?

Answers:


24

假设最高值仅出现一次,则另一种使用方式OFFSET(SQL Server 2012或更高版本):

SELECT * 
FROM tablename
ORDER BY column DESC 
OFFSET 1 ROW 
FETCH NEXT 1 ROW ONLY;

23

要获得表中第二高的唯一值,您可以使用

SELECT MIN(value)
FROM   (SELECT DISTINCT TOP (2) value
        FROM   tablename
        ORDER  BY value DESC)T
/*If only one distinct value return nothing. */
HAVING MIN(value) <> MAX(value);

13

通用解决方案如下所示:

;WITH CTE AS
(
    SELECT
        Col1
        , Col2
        , <AnyColumns>
        , ROW_NUMBER() OVER (ORDER BY <AnyColumns>) AS RowNum
    FROM <YourTable>
    WHERE <YourCondition>
)
SELECT *
FROM CTE
WHERE RowNum = 2 -- Or any condition which satisfies your problem

您还可以在此处定义范围,例如RowNum >= 10 AND RowNum <= 20。它将为您提供第10至20行以及所有必需的列。


7

您具有通常的最高技巧,例如:

select top 1 *
from (
    select top 2 *
    from my_table
    order by value desc
    ) t 
order by value asc 

或者,您也可以像这样使用CTE:

with CTE as
(
select value, ROW_NUMBER() over(order by value desc) as ord_id
from my_table
)
select value
from CTE
where ord_id = 2

或者,如果您使用的是SQLServer的最新版本(> = 2012),则应使用lag函数。

SELECT  top 1  lag(value, 1,0) OVER (ORDER BY value)  
FROM my_table
order by value desc

5

我会这样:

SELECT MAX(value)
FROM tablename
WHERE value < (SELECT MAX(value)
               FROM tablename)

1

您也可以使用ROW_NUMBER()加窗功能。如果要按目标值排序时获得第二项,则可以执行以下操作:

SELECT value 
FROM (
    SELECT 
        ROW_NUMBER() OVER (PARTITION BY NULL ORDER BY value DESC) as RN,
        value
    FROM my_table
) d
WHERE RN = 2

现在,如果您想获得第二高的值并且有重复项,则可能需要按值条目进行分组,以便仅获得不同的值。

SELECT value 
FROM (
    SELECT 
        ROW_NUMBER() OVER (PARTITION BY NULL ORDER BY value DESC) as RN,
        value
    FROM my_table
    GROUP BY value
) d
WHERE RN = 2

MIN(id)如果您需要知道具有第二高值的第一条记录的ID(假设您的数据集有两个60s和两个55s),则应该可以修改此方法以在内部选择中包括a 。


5
对于第二高的列,只需替换ROW_NUMBER()为更容易DENSE_RANK()-您还可以免费获得所有其他列。无需使用GROUP BY
ypercubeᵀᴹ
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.