To calculate the number of pages, we can use following simple algorithm:
If the number of query rows divisible by the number of records per page, the result of integer division one to the other gives the number of pages;
if there is a nonzero remainder of integer division of the query rows on the number of records on the page, the result of integer division adds one (the last page is incomplete).
This algorithm is implemented by standard means using the CASE operator:
To get to each row of query the page number on which it must fall, we can apply the same algorithm, but apply it is necessary not to the total number of rows (total), and row number. This row number we can get through a ranking ROW_NUMBER function, performing the required sorting by price: