select all rows except top row [duplicate]
Asked Answered
T

4

7

how do I return all rows from a table except the first row. Here is my sql statement:

Select Top(@TopWhat) * 
from tbl_SongsPlayed 
where Station = @Station 
order by DateTimePlayed DESC

How do I alter my SQL statement to return all rows except the first row.

Many thanks

Teri answered 22/2, 2013 at 20:39 Comment(2)
did you google?i just copied the title and search and found so many answers! here is one : #6027625Reduplication
what version of sql server?Troop
P
32

SQL 2012 also has the rather handy OFFSET clause:

Select Top(@TopWhat) *
from tbl_SongsPlayed 
where Station = @Station 
order by DateTimePlayed DESC
OFFSET 1 ROWS
Pincushion answered 22/2, 2013 at 20:45 Comment(0)
T
6

Depending on your database product, you can use row_number():

select *
from
(
  Select s.*,
    row_number() over(order by DateTimePlayed DESC) rn
  from tbl_SongsPlayed s
  where s.Station = @Station 
) src
where rn >1
Troop answered 22/2, 2013 at 20:41 Comment(0)
C
1

The EXCEPT operator (http://msdn.microsoft.com/en-us/library/ms188055.aspx)

Select Top(@TopWhat) *
from tbl_SongsPlayed 
Except  Select Top(1) *
from tbl_SongsPlayed 
where Station = @Station 
order by DateTimePlayed DESC

'Not In' was another clause that can be used.

Confucius answered 22/2, 2013 at 21:28 Comment(1)
The first subquery is neither filtered nor ordered. The result of the complete query may not be what the OP is after.Varicocele
S
0

Assuming you have a unique ID for tbl_SongsPlayed, you could do something like this:

// Filter the songs first
With SongsForStation
As   (
   Select *
   From   tbl_SongsPlayed
   Where  Station = @Station
)
// Get the songs
Select *
From   SongsForStation
Where  SongPlayId <> (
   // Get the top song, most recently played, so you can exclude it.
   Select Top 1 SongPlayId
   From   SongsForStation
   Order By DateTimePlayed Desc
   )
// Sort the rest of the songs.
Order By
   DateTimePlayed desc
        Where 
Seroka answered 22/2, 2013 at 20:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.