[英]SQL Server 2005 Query Help
I have a table and I want to get the row before the last one. 我有一张桌子,我想在最后一张桌子前得到这一行。 Eg 例如
KeyboardID KeyboardName
1 "DELL"
2 "HP"
3 "Viewsonic"
4 "Samsung"
select max(keyboardid) from keyboard -> will get the Samsung 从键盘上选择max(keyboardid)->将获得三星
My Question is how to get the Viewsonic Keyboard... 我的问题是如何获得Viewsonic键盘...
SELECT *
FROM (
SELECT *,
ROW_NUMBER() OVER (ORDER BY KeyboardId DESC) AS rn
FROM Table
) AS t
WHERE rn = 2;
or 要么
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (ORDER BY KeyboardId DESC) AS rn
FROM Table)
SELECT *
FROM cte
WHERE rn = 2;
or 要么
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
Actually have this as an interview question. 其实有这个作为面试的问题。 To get just the id: 要获取ID:
SELECT MAX(KeyboardID) as SecondPlaceID
FROM Keyboard
WHERE KeyboardID < (SELECT MAX(KeyboardID) FROM Keyboard)
or for the full row: 或整行:
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.