SQL查询找出涉及两个表的第三高工资

时间:2012-08-31 14:18:59

标签: sql-server-2008

我有两张桌子:

empid(primary key)
firstname
lastname
email

详细信息:

Did(primary key)
salary
designation
empid

现在我想选择工资第三高的员工的名字,姓氏,工资。

由于我是一个初学者,所以保持简单。

如果你能建议我找到一个可以找到解决方案的SQL查询练习的网站(我不需要一个在线翻译,我有SQL Server 2008来练习),那也很棒,我已经完成了w3schools(这是太棒了)但我现在需要练习,我尝试过sql.ex.ru但是没那么有用。

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT   top 1 P.*,a.salary 
FROM     Persons p
JOIN
         (select top 3 empid,salary from Details order by salary desc)a
ON       p.empid=a.empid
ORDER BY p.salary

;WITH CTE AS
 (SELECT *,
         ROW_NUMBER() OVER (ORDER BY SALARY DESC) AS ROW_NUM
 FROM DETAILS)
 SELECT * 
 FROM  PERSONS P
 JOIN  CTE C
 ON    P.EMPID=C.EMPID
 where c.ROW_NUM=3

答案 1 :(得分:1)

这是一个小技巧。它的作用是在每一行上添加一个序列号或行号,按工资给出排序。然后它只选择第三个:

select FirstName, LastName, Salary
from (select p.FirstName, p.LastName, d.salary,
             row_number() over (order by salary desc) as seqnum
      from persons p join
           details d
           on p.empid = d.empid
     ) t
where seqnum = 3

row_number()函数执行此计算。这是一个非常有用的功能,您可以添加到您的SQL知识。

答案 2 :(得分:0)

SELECT TOP 1 persons.FirstName, persons.LastName, Salary 
FROM persons inner join Details
ON persons.empid=Details.empid 
where Salary not in(SELECT TOP 2 Salary from Details ORDER BY Salary DESC)
order by Salary desc