code_junkie

What is the simplest SQL Query to find the second largest value?

Nov 10th, 2011
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. SELECT MAX( col )
  2. FROM table
  3. WHERE col < ( SELECT MAX( col )
  4. FROM table )
  5.  
  6. --filter out the max
  7. select max( col )
  8. from [table]
  9. where col < (
  10. select max( col )
  11. from [table] )
  12.  
  13. --sort top two then bottom one
  14. select top 1 col
  15. from (
  16. select top 2 col
  17. from [table]
  18. order by col) topTwo
  19. order by col desc
  20.  
  21. select col
  22. from (
  23. select ROW_NUMBER() over (order by col asc) as 'rowNum', col
  24. from [table] ) withRowNum
  25. where rowNum = 2
  26.  
  27. SELECT * FROM Table ORDER BY NumericalColumn DESC LIMIT 1 OFFSET 1
  28.  
  29. SELECT * FROM Table ORDER BY NumericalColumn DESC LIMIT (1, 1)
  30.  
  31. SELECT DISTINCT value FROM Table ORDER BY value DESC LIMIT 2
  32.  
  33. SELECT MIN(value) FROM (SELECT DISTINCT value FROM Table ORDER BY value DESC LIMIT 2) AS t
  34.  
  35. SELECT MIN([column]) AS [column]
  36. FROM (
  37. SELECT TOP 2 [column]
  38. FROM [Table]
  39. GROUP BY [column]
  40. ORDER BY [column] DESC
  41. ) a
  42.  
  43. SELECT `column` FROM `table` GROUP BY `column` ORDER BY `column` DESC LIMIT 1,1
  44.  
  45. select top 1 x
  46. from (
  47. select top 2 distinct x
  48. from y
  49. order by x desc
  50. ) z
  51. order by x
  52.  
  53. SELECT TOP 1 START AT 2 value from table ORDER BY value
  54.  
  55. Select * from x x1 where 1 = (select count(*) from x where x1.a < a)
  56.  
  57. select * from emp e where 3>=(select count(distinct salary)
  58. from emp where s.salary<=salary)
  59.  
  60. select top 1 MyIntColumn from MyTable
  61. where
  62. MyIntColumn <> (select top 1 MyIntColumn from MyTable order by MyIntColumn desc)
  63. order by MyIntColumn desc
  64.  
  65. select max([COLUMN_NAME]) from [TABLE_NAME] where [COLUMN_NAME] <
  66. ( select max([COLUMN_NAME]) from [TABLE_NAME] )
  67.  
  68. select min(sal) from emp where sal in
  69. (select TOP 2 (sal) from emp order by sal desc)
  70.  
  71. select max([COLUMN_NAME]) from [TABLE_NAME] where [COLUMN_NAME] **IN**
  72. ( select max([COLUMN_NAME]) from [TABLE_NAME] )
  73.  
  74. select max(COL_NAME) from TABLE_NAME where COL_NAME in
  75. (select COL_NAME from TABLE_NAME where COL_NAME < (select max(COL_NAME) from TABLE_NAME));
  76.  
  77. SELECT MAX(col) FROM table WHERE col NOT IN (SELECT MAX(col) FROM table);
Add Comment
Please, Sign In to add comment