1532. The Most Recent Three Orders

https://leetcode.com/problems/the-most-recent-three-orders

Description

Table: Customers

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| customer\_id   | int     |
| name          | varchar |
+---------------+---------+
customer\_id is the primary key for this table.
This table contains information about customers.

Table: Orders

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| order\_id      | int     |
| order\_date    | date    |
| customer\_id   | int     |
| cost          | int     |
+---------------+---------+
order\_id is the primary key for this table.
This table contains information about the orders made by customer\_id.
Each customer has **one order per day**.

Write an SQL query to find the most recent 3 orders of each user. If a user ordered less than 3 orders return all of their orders.

Return the result table sorted by customer_name in ascending order and in case of a tie by the customer_id in ascending order. If there still a tie, order them by the order_date in descending order.

The query result format is in the following example:

Follow-up: Can you write a general solution for the most recent n orders?

ac

Last updated

Was this helpful?