问题
Possible Duplicate:
ROW_NUMBER() without over in SQL
I have a grid with sorting on each column and have to show only 50 rows at a time.
I am using sql server 2005 as database.
Now there is ROW_NUMBER function in sql server 2005 to filter the data with row number but Over(order by [Column]) is mandatory to use. In my case I have to sort my grid with different columns so I can not use the static columns name in order by clause. The restriction is , I have to use static query.
Can you guys help me out on this problem?
回答1:
Use several ROW_NUMBER clauses per column and choose the relevant one:
....
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 use a CASE expression. Note: all datatypes must be compatible
ROW_NUMBER() OVER (ORDER BY CASE @sort
WHEN 1 THEN [Column1]
WHEN 1 THEN [Column2]
WHEN 1 THEN [Column3]
...
END
OR If you really want an arbitrary row number then do this:
ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rn
回答2:
I found some way to do it.
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
来源:https://stackoverflow.com/questions/12914888/need-to-use-row-number-without-over-in-sqlserver-2005