我正在分享我的SQL如果有人比这更好,请在这里发帖。
要在查询下方获得第一笔最高薪水:
select salary from employee order by salary desc limit 1;
要在查询下方获得第二高薪:
select salary from employee order by salary desc limit 1,1;
要在查询下方获得第三高薪:
select salary from employee order by salary desc limit 2,1;
答案 0 :(得分:4)
您可以使用此查询获得前N个工资,其中N
是第N个最高工资。
SELECT *
FROM Employee Emp1
WHERE (N) = (
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary >= Emp1.Salary
)
答案 1 :(得分:2)
你的代码很好......除了工资的倍数存在之外......即如果前10名工资是1000,那么最高薪水= 1000,前3名= 1000等等
使用分组...
select salary
from employee
GROUP BY salary
order by salary desc limit 1;
或不同的......
select DISTINCT(salary)
from employee
order by salary desc limit 1;
答案 2 :(得分:1)
我会做以下事情:
SELECT TOP 1 FROM employee ORDER BY salary desc
获得第二高的
SELECT TOP 1 FROM employee ORDER BY salary DESC OFFSET 1
获得第三个
SELECT TOP 1 FROM employee ORDER BY salary DESC OFFSET 2
但是如果你打算在同一段代码中使用所有三个代码,我建议同时将它们全部3个,因为这会让你执行2个队列。我想建议一个对开的查询来获得前3名最高薪水
SELECT TOP 3 FROM employee ORDER BY salary DESC
答案 3 :(得分:1)
为什么不使用像这样的查询
SELECT * FROM employee ORDER BY salary DESC LIMIT 3;
当你解析它时,你可以走到每一行。我认为使用LIMIT 3
比使用TOP 3
更好。推荐Here