Bootstrap

mysql取第二大_mysql – SQL:从一行列中获取第二大值

我担心,如果没有公用表表达式和/或窗口函数,并且不需要编写过程,这在MySQL中会变得非常冗长

SELECT t.id, t.val second_largest

-- unpivot your columns into a table

FROM (

SELECT id, col1 val FROM my_table UNION ALL

SELECT id, col2 FROM my_table UNION ALL

SELECT id, col3 FROM my_table UNION ALL

SELECT id, col4 FROM my_table UNION ALL

SELECT id, coln FROM my_table

) t

-- retain only those records, where there exists exactly one record with a

-- column value greater than any other column value with the same id

WHERE 1 = (

SELECT COUNT(*)

-- Here, use unions to be sure that every value appears exactly once

FROM (

SELECT id, col1 val FROM my_table UNION

SELECT id, col2 FROM my_table UNION

SELECT id, col3 FROM my_table UNION

SELECT id, col4 FROM my_table UNION

SELECT id, coln FROM my_table

) u

WHERE t.id = u.id

AND t.val < u.val

)

这是检查它的SQLFiddle(感谢bluefeet对于模式的单挑!).即使最大列值出现多次,上述解决方案也会在每一行中找到第二大列值.

;