需要SQLSERVER 2005 [复制]使用ROW_NUMBER无过(need to use RO

2019-09-24 04:25发布

可能重复:
ROW_NUMBER()不超过在SQL

我有一个网格,每列进行排序,并在某一时刻只显示50行。

我使用SQL Server 2005数据库。

现在有ROW_NUMBER函数SQL Server 2005中筛选与行号,但该数据Over(order by [Column])强制使用。 在我来说,我有我的网格,不同的列进行排序,所以我不能by子句才能使用静态列名。 该限制是,我必须使用静态查询。

你们可以帮我这个问题?

Answer 1:

使用几个ROW_NUMBER条款每列,并选择相关的一个:

....
    ROW_NUMBER() OVER (ORDER BY [Column1]) as rn1,
    ROW_NUMBER() OVER (ORDER BY [Column2]) as rn2,
    ROW_NUMBER() OVER (ORDER BY [Column3]) as rn3,
    ROW_NUMBER() OVER (ORDER BY [Column4]) as rn4
....

使用CASE表达式。 注:所有数据类型必须兼容

ROW_NUMBER() OVER (ORDER BY CASE @sort
                     WHEN 1 THEN [Column1]
                     WHEN 1 THEN [Column2]
                     WHEN 1 THEN [Column3]
                     ...
                   END

或者如果你真的想要的任意行编号,然后执行以下操作:

ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rn


Answer 2:

我找到了一些方法来做到这一点。

SELECT
  OrderID, CustomerID, EmployeeID, OrderDate, ShippedDate,
  @Offset, @Limit, @SortColumn, @SortDirection
FROM
  Orders
WHERE
  ROW_NUMBER() OVER 
  (
    ORDER BY
      /* same expression as in the ORDER BY of the whole query */
  ) BETWEEN (@PageNum - 1) * @PageSize + 1 AND @PageNum * @PageSize 
  /* AND more conditions ... */
ORDER BY
  CASE WHEN @SortDirection = 'A' THEN
    CASE @SortColumn 
      WHEN 'OrderID'    THEN OrderID
      WHEN 'CustomerID' THEN CustomerID
      /* more... */
    END
  END,
  CASE WHEN @SortDirection = 'D' THEN
    CASE @SortColumn 
      WHEN 'OrderID'    THEN OrderID
      WHEN 'CustomerID' THEN CustomerID
      /* more... */
    END 
  END DESC


文章来源: need to use ROW_NUMBER without over in sqlserver 2005 [duplicate]