2016-11-03 105 views
2

我正在使用Microsoft SQL Server 2012,並且我有這個查詢(下面)。它正確地返回一切,但我不知道如何獲得只有第四行返回。獲取查詢結果的第4行

我知道如何做一個簡單的查詢,但與這個複雜的查詢我不知道如何只返回第4行。由於我使用的是MS SQL Server,因此我無法使用限制/偏移量。如何以及在哪裏放置代碼以僅打印第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]; 

回答

6

使用CTE與ROW_NUMBER()

;WITH Cte AS 
(
    SELECT Col1, Col2, ..., 
     ROW_NUMBER() OVER (ORDER BY ...) AS RowNum 
    FROM Table 
) 
SELECT * 
FROM Cte 
WHERE RowNum = 4 
+0

這就是我該怎麼做的! –

1

您可以使用TOP這種方式(第一隻選擇了4 rown和排序倒序選擇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 
2

你也可以使用OFFSET/FETCH關鍵字。

SELECT * 
    FROM yourTable 
ORDER by yourSortColumn 
OFFSET 3 ROWS -- Skip Three rows. 
FETCH FIRST 1 ROW ONLY;