经常遇到关于第二大的计算,如找到销售量第二大的id等等这类问题。
一下是我的学习总结,有些来自网络,出处会给出详细的链接,方便寻找源码。
来源https://leetcode.com/problems/second-highest-salary/description/
SELECT
(SELECT DISTINCT
Salary
FROM
Employee
ORDER BY Salary DESC
LIMIT 1 OFFSET 1) AS SecondHighestSalary
;
保证了Salary只有唯一的输出,避免多个第二高的情况。
SELECT
IFNULL(
(SELECT DISTINCT Salary
FROM Employee
ORDER BY Salary DESC
LIMIT 1 OFFSET 1),
NULL) AS SecondHighestSalary
解决了为空的问题,为空就输出NULL
SELECT MAX(Salary) AS SecondHighestSalary
FROM Employee
WHERE Salary < (SELECT MAX(Salary) FROM Employee)
参考http://blog.csdn.net/u010479690/article/details/25053937
为了方便自己日后参看,将http://blog.csdn.net/u010479690/article/details/25053937中的内容转过来。
mysql
SELECT MAX(vcid) FROM msdtb1701
WHERE vcid < (SELECT MAX(vcid) FROM msdtb1701)
或
SELECT MAX(vcid) FROM msdtb1701
WHERE vcid NOT IN (SELECT MAX(vcid) FROM msdtb1701)
SELECT vcuser ,vcid FROM msdtb1701
WHERE vcid=
(SELECT MAX(vcid) FROM msdtb1701 WHERE vcid
NOT IN (SELECT MAX(vcid) FROM msdtb1701))
SELECT MAX(vcid) FROM msdtb1701
WHERE vcid < (SELECT MAX(vcid) FROM msdtb1701 WHERE vcid
NOT IN (SELECT MAX(vcid) FROM msdtb1701))
SELECT vcid,vcuser FROM msdtb1701 ORDER BY vcid DESC LIMIT 3
注意:依照此数值调整限制输出行数
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
DECLARE M INT;
SET M=N-1;
RETURN (
# Write your MySQL query statement below.
SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT M, 1
);
END
Sql Server
select TOP N * from tablename where
ORACLE
SELECT * FROM TABLE1 WHERE ROWNUM<=N