除了顶部行,选择所有行

7

如何从表中返回除第一行以外的所有行。 这是我的sql语句:

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

如何修改我的SQL语句以返回除第一行之外的所有行。

非常感谢


1
你有谷歌过吗?我只是复制了标题并搜索,找到了很多答案!这里有一个:https://dev59.com/l2025IYBdhLWcg3wZlLd - Arash
1
什么版本的SQL Server? - Taryn
4个回答

32

SQL 2012 还有一个非常方便的 OFFSET 子句:

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

那是一个不错的功能。 - Kaf
啊,真可惜他们要这么久才实现... MySQL 已经有好几年了 :( - chrisb
做得很棒!+1 - Aleksandr Fedorenko
1
但是我正在使用SQL 2005...偏移量不起作用。那个版本有什么解决方法? - D-Dawgg
ROW_NUMBER就是在这种情况下的最佳选择。请参见@bluefeet上面的答案。 - chrisb

6

根据您使用的数据库产品,您可以使用 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

2
正确的 order by 语句是 order by DateTimePlayed desc - Gordon Linoff
1
@GordonLinoff 没错,已修复。 - Taryn

1

已经有'Chrisb'提供了一个非常简洁的答案。但是您也可以尝试使用以下方法...

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

“不在”是另一个可以使用的从句。

2
第一个子查询既没有过滤也没有排序。完整查询的结果可能不是 OP 所想要的。 - Andriy M
我需要从一个表值函数中返回第二行,这帮了我大忙! - Samra

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 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接