2013-02-22 65 views
4

如何返回除第一行以外的表中的所有行。這是我的sql語句:選擇除最上面一行以外的所有行

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

如何更改我的SQL語句以返回除第一行以外的所有行。

非常感謝

+0

你google嗎?我剛剛複製標題和搜索,發現如此多的答案!這裏是一個:http://stackoverflow.com/questions/6027125/selecting-the-row-of-table-except-the-first-one – Arash 2013-02-22 20:42:01

+0

什麼版本的SQL服務器? – Taryn 2013-02-22 21:26:42

回答

5

根據您的數據庫產品,您可以使用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 
+1

正確的'by by'語句是'DateTimePlayed desc'命令。 – 2013-02-22 21:01:05

+1

@GordonLinoff你是對的,修好了 – Taryn 2013-02-22 21:01:31

0

假設你有一個tbl_SongsPlayed一個唯一的ID,你可以做這樣的事情:

// 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 
18

SQL 2012還具有相當方便的OFFSET子句:

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

+1對於不安 – 2013-02-22 21:06:47

+0

這是一個不錯的功能 – Kaf 2013-02-22 21:22:34

+0

是的。慚愧,他們花了這麼長的時間來實現... MySQL已經有它多年:( – chrisb 2013-02-22 21:24:55

0

已經'克里斯布'給了一個非常簡潔的答案。但你也可以試試這個...

的EXCEPT操作數(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 

「不在」是可以使用的一個條款。

+1

第一個子查詢既沒有過濾也沒有排序,完整查詢的結果可能不是OP的結果。 – 2013-02-22 22:42:12

相關問題