我正在使用Microsoft SQL Server 2012,我有这个查询(如下)。它正确返回所有内容,但我无法弄清楚如何只返回第4行。
我知道如何通过一个简单的查询来完成它,但是对于这个复杂的查询,我不知道如何只返回第4行。由于我使用的是MS SQL Server,因此无法使用Limit / Offset。如何以及在何处放置代码以仅打印第4行?我很难过。感谢。
SELECT T.[First Name],
T.[Last Name],
T.[Middle Name],
T.[Country Name],
T.[Designation Name],
Salary.Emp_Salary AS 'Current Salary'
FROM
(
SELECT
Emp_First_Name AS "First Name",
Emp_Last_Name AS "Last Name",
Emp_Middle_Name AS "Middle Name",
Country_Name AS "Country Name",
Desig_Name as "Designation Name",
MAX(Emp_Salary_Change_Year) AS "Time"
FROM Employee_Details
INNER JOIN Country ON Employee_Details.Emp_Country_Id = Country.Country_Id
INNER JOIN State ON Employee_Details.Emp_State_Id = State.State_Id
INNER JOIN Designation ON Employee_Details.Desig_Id = Designation.Desig_Id
INNER JOIN Salary ON Employee_Details.Emp_Id = Salary.Emp_Id
GROUP BY Emp_First_Name, Emp_Last_Name,
Emp_Middle_Name, Country_Name, Desig_Name) AS T
INNER JOIN Salary ON T.Time = Salary.Emp_Salary_Change_Year
ORDER BY [Current Salary];
答案 0 :(得分:6)
使用带有ROW_NUMBER()
的CTEcontact_emails = {
'Sue Reyn' : 's.reyn@email.com',
'Mike Filt': 'mike.filt@bmail.com',
'Nate Arty': 'narty042@nmail.com'
}
for email in contact_emails:
print('%s is %s' % (email, contact_emails(email)))
答案 1 :(得分:2)
您也可以使用OFFSET / FETCH关键字。
SELECT *
FROM yourTable
ORDER by yourSortColumn
OFFSET 3 ROWS -- Skip Three rows.
FETCH FIRST 1 ROW ONLY;
答案 2 :(得分:1)
你可以这样使用TOP(首先你只选择4个rown,而排序desc选择1行)
select TOP 1 from (
SELECT TOP 4 T.[First Name],
T.[Last Name],
T.[Middle Name],
T.[Country Name],
T.[Designation Name],
Salary.Emp_Salary AS 'Current Salary'
FROM
(
SELECT
........
) AS T
INNER JOIN Salary ON T.Time = Salary.Emp_Salary_Change_Year
ORDER BY [Current Salary])
ORDER BY [Current Salary] DESC