The query below fetches a subset of rows from a table starting at row 10 and ending at row 20. In addition, to save a query I need to return the total number of rows in the table. This is the best solution that I could think of. Are there any more efficient/elegant ways? In particular, I do not like the partition by 1
part.
select *
from (select count(*) over (partition by 1) as [count],
row_number() over (order by [Name],[Description]) as [row],
*
from [Products]) as t
where row between 10 and 20
If you don't like it, remove it!
select *
from (select count(*) over () as [count],
row_number() over (order by [Name],[Description]) as [row],
*
from [Products]) as t
where row between 10 and 20
However, that aside, the query isn't optimal. You should do the count the traditional way.
select *
from (select count(*) as [count]
from [Products]) X
cross join (
select row_number() over (order by [Name],[Description]) as [row],
*
from [Products]) as t
where row between 10 and 20
You can put both of these together and press Ctrl-M, then execute. The plans will look quite different.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.