问题
Select id, name, ROW_NUMBER() OVER (ORDER BY id asc) as 'RowNo'
from customers
where RowNo between 50 AND 60
I am trying to select a subset of rows between 50 and 60 . The problem is 'RowNo' is an invalid column name.
Thank you
Using SQL SERVER 2008 R2
回答1:
Use your query as subquery like bellow:
select * from (
Select id, name, ROW_NUMBER() OVER (ORDER BY id asc) as [RowNo]
from customers
) t
where RowNo between 50 AND 60
You can use CTE as well but whether to choose one over another read Difference between CTE and SubQuery? and check execution plan.
回答2:
You need to do something like this:
;WITH PaginatingData AS
(
Select id, name, ROW_NUMBER() OVER (ORDER BY id asc) as 'RowNo'
from customers
)
SELECT *
FROM PaginatingData
where RowNo between 50 AND 60
Use a CTE (Common Table Expression - sort of an "inline view") as a "wrapper" so that your RowNo
becomes a valid column name.
As an outlook - with SQL Server 2012, you'd be able to write something like this:
SELECT
id, name
FROM
dbo.customers
ORDER BY
id
OFFSET 50 ROWS
FETCH NEXT 10 ROWS ONLY
SQL Server 2012 will have this ANSI SQL Standard compliant notation to do paging directly based on an ORDER BY
clause. See this blog post (or tons of others) for more info and more samples.
来源:https://stackoverflow.com/questions/9328753/select-subset-of-rows-using-row-number