有人可以提出创新的查询来选择第二高薪,来自表格“EMP”,其中包含三个“NOT NULL”字段,sal(薪水),姓名,empno(员工编号)?
我有一个:
Select sal
from EMP A
where 1 = (select count(DISTINCT SAL) from EMP B whre A.sal < B.sal);
select DISTINCT sal
from emp a
where 1 = (select count(DISTINCT sal) from emp b where a.sal < b.sal);
答案 0 :(得分:3)
select empno,
name,
salary
from (
select empno,
name,
salary,
dense_rank() over (order by salary desc) as rnk
from employee
) t
where rnk = 2;
答案 1 :(得分:0)
SOF已经回答了这个问题,你必须决定它们是否足够创新以满足你的需求。
What is the simplest SQL Query to find the second largest value?
How to get second largest or third largest entry from a table
SELECT emp_salary,R
FROM (SELECT ROWNUM R,emp_salary
FROM (SELECT emp_salary
FROM Employee
ORDER BY emp_salary DESC
)
)
WHERE R=2
这应该按你的意愿工作。您可以替换R的值来查找任何值。 R = 2给出第二高,R = 3给出第三高。
你可以在这里试试小提琴http://sqlfiddle.com/#!4/a6f42/14
答案 2 :(得分:0)
查询以找到第二高薪。
SELECT * FROM EMP WHERE SAL IN(SELECT MAX(SAL) FROM EMP WHERE SAL NOT IN (SELECT MAX(SAL) FROM EMP));
答案 3 :(得分:0)
SELECT * FROM EMP A
WHERE 2= (SELECT COUNT(*) FROM EMP B WHERE B.SAL >=A.SAL)
如果2名员工的薪水高于第二名,那么使用3之后的where子句而不是2。
答案 4 :(得分:0)
select top (1) sal from Emp where sal<(select max(sal) from emp) order by sal desc
在上面的查询中,我们首先按降序对所有工资进行排序,以便在顶部获得最高薪水,然后我们选择最高薪水,该薪水低于该栏目中的最高薪水。
答案 5 :(得分:0)
SELECT MAX(esalary)
FROM emp
WHERE esalary <
(SELECT MAX(esalary)
FROM emp);
SELECT MAX(esalary)
FROM emp
WHERE esalary NOT IN
(SELECT MAX(esalary)
FROM emp);
答案 6 :(得分:0)
这是最有利的面试问题。你可以用不同的方式解决这个问题 - 查询1:
select MAX(Sal) from Employee WHERE Sal NOT IN (select MAX(Sal) from Employee );
查询2:
WITH CTE AS (
SELECT Ename, sal,
ROW_NUMBER() OVER(ORDER BY sal DESC) as RN
FROM Employee
)
SELECT Ename, sal
FROM CTE
WHERE RN = 2
查询3:如果你想获得第N个最高薪水,你只需要提到N(1/2/3/4 / .. N)代替2。
select A.Ename, A.sal from Employee A
where 2 = (select count(*) from Employee B where B.EmpNo >= A.EmpNo)
你可以在这里找到更多答案。 https://knowledgebase.techandmate.com/answers/55
谢谢,
答案 7 :(得分:-1)
;WITH cte
AS (
SELECT *,
ROW_NUMBER() OVER (
ORDER BY [salary] DESC
) AS rowid
FROM [Employee].[DimEmployeeDetails]
)
SELECT *
FROM cte
WHERE rowid = 2