[英]SQL Server 2005 Query Help
我有一張桌子,我想在最后一張桌子前得到這一行。 例如
KeyboardID KeyboardName
1 "DELL"
2 "HP"
3 "Viewsonic"
4 "Samsung"
從鍵盤上選擇max(keyboardid)->將獲得三星
我的問題是如何獲得Viewsonic鍵盤...
SELECT *
FROM (
SELECT *,
ROW_NUMBER() OVER (ORDER BY KeyboardId DESC) AS rn
FROM Table
) AS t
WHERE rn = 2;
要么
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (ORDER BY KeyboardId DESC) AS rn
FROM Table)
SELECT *
FROM cte
WHERE rn = 2;
要么
SELECT TOP(1) *
FROM (
SELECT TOP(2) *
FROM Table
ORDER BY KeyboardId DESC) AS t
ORDER BY KeyboardId;
SELECT TOP 1 *
FROM Keyboard
WHERE KeyboardID < (SELECT MAX(KeyboardID) FROM Keyboard)
ORDER BY KeyboardID DESC
其實有這個作為面試的問題。 要獲取ID:
SELECT MAX(KeyboardID) as SecondPlaceID
FROM Keyboard
WHERE KeyboardID < (SELECT MAX(KeyboardID) FROM Keyboard)
或整行:
SELECT *
FROM Keyboard
WHERE KeyboardID = (SELECT MAX(KeyboardID)
FROM Keyboard
WHERE KeyboardID <
(SELECT MAX(KeyboardID) FROM Keyboard))
Declare @MaxID Int
Select @MaxID = max(KeyboardID) from tblFacts
Select top 1 * from tblFacts where KeyBoardID < @MaxID
Order by @MaxID desc
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.