2017-10-05 66 views
0
select top 20 * 
from dbo.DUTs D 
inner join dbo.Statuses S on d.StatusID = s.StatusID 
where s.Description = 'Active' 

上面的SQL查詢返回前20行,如何從上述查詢的結果中獲得第n行?我查看以前的帖子,發現第n行,並不清楚用於我的目的。使用sql查找第n行

謝謝。

+1

時退房SQL中的OFFSET關鍵字。它用於分頁記錄,但可能對您有用。 – xDJR1875

+1

[我如何獲得SQL Server表中的第n行?](https://stackoverflow.com/questions/2273558/how-do-i-get-the-nth-row-in-a- sql-server-table) – Valli

回答

1

行順序是任意的,所以我會添加一個ORDER BY表達式。然後,你可以這樣做:

SELECT TOP 1 * FROM (SELECT TOP 20 * FROM ... ORDER BY d.StatusID) AS d ORDER BY d.StatusID DESC 

得到第20行。

您還可以使用OFFSET像:

SELECT * FROM ... ORDER BY d.StatusID OFFSET 19 ROWS FETCH NEXT 1 ROWS ONLY 

還有第三個選項:

SELECT * FROM (SELECT *, rownum = ROW_NUMBER() OVER (ORDER BY d.StatusID) FROM ...) AS a WHERE rownum = 20 
0

我傾向於使用熱膨脹係數與ROW_NUMBER()函數來得到我列出順序編號。正如@zambonee所說的,無論哪種方式,您都需要一個ORDER BY子句,或者SQL可以每次都以不同的順序放置它們。它通常不會,但是沒有自己訂購,你不能保證兩次獲得同樣的東西。在這裏,我假設有一個[DateCreated]字段(DATETIME NOT NULL DEFAULT GETDATE()),這通常是一個好主意,所以您知道該記錄何時輸入。這是說「給我的那張桌子的一切,並添加行號與最近的戰績爲#1」:

; WITH AllDUTs 
AS (
    SELECT * 
      , DateCreatedRank = ROW_NUMBER() OVER(ORDER BY [DateCreated] DESC) 
    FROM dbo.DUTs D 
      INNER JOIN dbo.Statuses S ON D.StatusID = S.StatusID 
    WHERE S.Description = 'Active' 
    ) 
SELECT * 
FROM AllDUTs 
WHERE AllDUTs.DateCreatedRank = 20; 
+0

謝謝大家,及時回覆。我得到了它的工作。再次感謝。 – user2329418

0
SELECT * FROM (SELECT * FROM EMP ORDER BY ROWID DESC) WHERE ROWNUM<11 
0

它的另一個示例:

SELECT * ,CASE WHEN COUNT(0)OVER() =ROW_NUMBER()OVER(ORDER BY number) THEN 1 ELSE 0 END IsNth 
FROM ( 
    select top 10 * 
    from master.dbo.spt_values AS d 
    where d.type='P' 
) AS t 
 
+------+--------+------+-----+------+--------+-------+ 
| name | number | type | low | high | status | IsNth | 
+------+--------+------+-----+------+--------+-------+ 
| NULL | 0  | P | 1 | 1 | 0  | 0  | 
| NULL | 1  | P | 1 | 2 | 0  | 0  | 
| NULL | 2  | P | 1 | 4 | 0  | 0  | 
| NULL | 3  | P | 1 | 8 | 0  | 0  | 
| NULL | 4  | P | 1 | 16 | 0  | 0  | 
| NULL | 5  | P | 1 | 32 | 0  | 0  | 
| NULL | 6  | P | 1 | 64 | 0  | 0  | 
| NULL | 7  | P | 1 | 128 | 0  | 0  | 
| NULL | 8  | P | 2 | 1 | 0  | 0  | 
| NULL | 9  | P | 2 | 2 | 0  | 1  | 
+------+--------+------+-----+------+--------+-------+