我有一个网格,每列都有排序,一次只能显示50行。
我使用sql server 2005作为数据库。
现在sql server 2005中有ROW_NUMBER函数来过滤带行号的数据,但必须使用Over(order by [Column])
。在我的情况下,我必须使用不同的列对网格进行排序,因此我不能在order by子句中使用静态列名称。限制是,我必须使用静态查询。
你们可以帮我解决这个问题吗?
答案 0 :(得分:4)
每列使用几个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
....
OR 使用CASE表达式。注意:所有数据类型必须兼容
ROW_NUMBER() OVER (ORDER BY CASE @sort
WHEN 1 THEN [Column1]
WHEN 1 THEN [Column2]
WHEN 1 THEN [Column3]
...
END
OR 如果您确实需要任意行号,请执行以下操作:
ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rn
答案 1 :(得分:0)
我找到了一些方法来做到这一点。
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