2016-07-31 77 views
3

什麼是SQL查詢爲每個Id#選擇第4行?在SQL Server中,如何挑選第4行?

它不是前4行的記錄。我正在嘗試爲每個ID僅選擇第4行的記錄/列。根據您的頂部

定義
+0

行按升序還是降序排列?你能舉一個例子說明輸出應該如何。 –

+0

每個帳單ID都有幾行交易。我只需要從頂部選擇第四行。 – goofyui

+0

如果你正在使用MySQL,那麼有限制子句來設置偏移n檢索行數 –

回答

7

使用row_number功能行:

SELECT * 
FROM 
    (SELECT 
     m.CityId, m.Country, m.Location, m.NoofDweller, 
     ROW_NUMBER() OVER (ORDER BY Country ASC) AS RowNumber 
    FROM 
     Cities m 
    WHERE 
     m.Country = 3 -- Just pass the required ID of the table 
    ) AS Details 
WHERE 
    RowNumber = 4 -- Gets details of the 4th row of the given ID 
1

您可以使用下面的查詢,並通過該表的所需的ID在分區

With cte as 
(
    select 
     *, 
     row_number() over (partition by id order by id) as rownum 
    from 
     table 
) 
select * 
from cte 
where rownum = 4 

更改爲了通過獲得特定的第4名: