【问题标题】:select all rows except top row [duplicate]选择除顶行以外的所有行[重复]
【发布时间】:2013-02-08 13:55:03
【问题描述】:

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

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

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

非常感谢

【问题讨论】:

标签: sql sql-server rows


【解决方案1】:

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

【讨论】:

  • 正确的order by 语句是order by DateTimePlayed desc
  • @GordonLinoff 你是对的,已修复
【解决方案2】:

假设您拥有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 

【讨论】:

    【解决方案3】:

    SQL 2012 也有相当方便的 OFFSET 子句:

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

    【讨论】:

    • 这是一个不错的功能
    • 是的。可惜他们花了这么长时间才实现......mysql已经拥有它多年了:(
    • 好方法! +1
    • 但我使用的是 SQL 2005...offset 不起作用。该版本的解决方法是什么?
    • ROW_NUMBER 是在这种情况下要走的路。请参阅上面@bluefeet 的答案。
    【解决方案4】:

    '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
    

    'Not In' 是另一个可以使用的子句。

    【讨论】:

    • 第一个子查询既没有过滤也没有排序。完整查询的结果可能不是 OP 所追求的。
    • 我需要由表值函数返回的第二行,这对我有帮助!
    猜你喜欢
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    • 2015-06-29
    相关资源
    最近更新 更多