我有一张桌子,我希望在最后一排之前得到这一行。 例如
KeyboardID KeyboardName
1 "DELL"
2 "HP"
3 "Viewsonic"
4 "Samsung"
从键盘选择max(keyboardid) - >将获得三星
我的问题是如何获得Viewsonic键盘......
答案 0 :(得分:3)
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;
答案 1 :(得分:2)
SELECT TOP 1 *
FROM Keyboard
WHERE KeyboardID < (SELECT MAX(KeyboardID) FROM Keyboard)
ORDER BY KeyboardID DESC
答案 2 :(得分:2)
实际上这是一个面试问题。获得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))
答案 3 :(得分:0)
Declare @MaxID Int
Select @MaxID = max(KeyboardID) from tblFacts
Select top 1 * from tblFacts where KeyBoardID < @MaxID
Order by @MaxID desc