views:

60

answers:

4

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

My Question is how to get the Viewsonic Keyboard...

A: 
Declare @MaxID Int
Select @MaxID = max(KeyboardID) from tblFacts

Select top 1 * from tblFacts where KeyBoardID < @MaxID
Order by @MaxID desc
u07ch
That would return "DELL"...ORDER BY needs to be DESC
AdaTheDev
+2  A: 
SELECT TOP 1 *
FROM Keyboard
WHERE KeyboardID < (SELECT MAX(KeyboardID) FROM Keyboard)
ORDER BY KeyboardID DESC
AdaTheDev
+3  A: 
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;
Remus Rusanu
Hurrah for solutions without aggregates...
gbn
+2  A: 

Actually have this as an interview question. To get just the 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))
JBrooks