从表中选择除最后一行之外的前5行

时间:2013-10-12 18:48:35

标签: sql sql-server

我需要从表中选择除MS SQL Server中最后一条记录之外的最后5行。

换句话说:

SELECT TOP 5 * 
FROM table 
ORDER BY column DESC 

但不考虑此选择中的表格最后一条记录。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

SQL Fiddle Example

使用以下代码可以在MS SQL Server 2012中轻松实现:

BEGIN

  DECLARE
    @OFFSET int = 1,
    @LIMIT int = 5

  -- SQL Server 2012+
  SELECT id, name 
  FROM t 
  ORDER BY name DESC -- DESC because you want the list upside down
  OFFSET @OFFSET ROWS -- skipped rows
  FETCH NEXT @LIMIT ROWS ONLY -- number of rows

END;


对于较旧的SQL Server版本,请使用:

BEGIN

  DECLARE
    @OFFSET int = 1,
    @LIMIT int = 5

  -- SQL Server 2008
  ;WITH cte AS
  (
    SELECT
      id,
      name,
      ROW_NUMBER() OVER (ORDER BY name DESC) AS RowNum -- DESC because you want the list upside down
  FROM t
  )
  SELECT id, name
  FROM cte
  WHERE RowNum > @OFFSET
    AND RowNum <= @OFFSET + @Limit

END