Print all details of the 16th order placed by each customer if any.
How to print exact 16th Order?
SELECT COUNT(orderId)
FROM orders
GROUP BY CustomerID
ORDER BY CustomerID;
Print all details of the 16th order placed by each customer if any.
How to print exact 16th Order?
SELECT COUNT(orderId)
FROM orders
GROUP BY CustomerID
ORDER BY CustomerID;
3
Answers
We can use a
CTE
andRANK
to create a list of all orderId’s, customerID’s and their "order" as you named it.Then we fetch those entries from the entire result whose order is 16.
For customerID’s having less than 16 orders, nothing will be selected.
We can also use
ROW_NUMBER
instead ofRANK
in the above query, this makes no difference in your use case.You can just use offset like:
and set the
OFFSET
value to 15 so it skips the first 15 values and prints from the 16th value and limit it to only one row by setting theLIMIT
value to 1