0

I have two tables:

Persons:

empid(primary key)
firstname
lastname
email

Details:

Did(primary key)
salary
designation
empid

Now I want to select firstname, lastname, salary of the employee with the 3rd highest salary.

KEEP IT SIMPLE SINCE I AM A BEGINNER.

Also it would be great if you can suggest me a site where I can find SQL query exercises with solutions (I do not need an online interpreter, I have SQL Server 2008 to practice on ), I have completed w3schools (which was awesome) but I need exercises now, I tried sql.ex.ru but it was not that helpful.

4

3 回答 3

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 知识中。

于 2012-08-31T15:24:51.070 回答
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
于 2012-08-31T14:26:24.417 回答
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
于 2012-08-31T14:39:11.280 回答