SQL query for paging received records

150 views Asked by At

I want to write a query that receives informations about customers and their orders from another table and show them in this way:

Customer 1
 Customer 1 Order 1
 Customer 1 Order 2
Customer 2
 Order 1 Customer 2
Customer 3
 Order 1 Customer 3
....

And I want to do paging by Customers. For example - if I define items per page = 10, I want to show 10 customers, no matter how many orders they had.

I prepared this query but I think it's not gonna work properly and I don't know how to solve this..

var result = db.Page<Customer>(pageNumber, 10, "SELECT c.*, o.* FROM Customers c JOIN Orders o 
ON o.Id = c.Id");
1

There are 1 answers

4
Gordon Linoff On BEST ANSWER

You can use dense_rank() and filter on that:

SELECT c.*, o.*, DENSE_RANK() OVER (ORDER BY c.id) as seqnum
FROM Customers c JOIN 
     Orders o 
     ON o.Customer_Id = c.Id;

You need to use WHERE for filtering, rather than LIMIT or FETCH or whatever.