cswork / libraryOpen practice workspace

Coding questions · Amazon

Identify First Daily Order for Each Merchant

This question evaluates proficiency in data manipulation with SQL and related tools, focusing on identifying the first transaction per merchant for each calendar date and handling ordering and deduplication within grouped transactional records.

Orders

+----------+-------------+---------+------------+
| order_id | merchant_id | amount  | order_date |
+----------+-------------+---------+------------+
| 101      | M01         | 120.50  | 2023-05-01 |
| 102      | M02         |  75.00  | 2023-05-01 |
| 103      | M01         |  90.00  | 2023-05-02 |
| 104      | M03         | 250.00  | 2023-05-02 |
| 105      | M01         | 110.00  | 2023-05-03 |
+----------+-------------+---------+------------+
Scenario

E-commerce platform wants to know which order was each merchant’s first transaction on any given day.

Question

Using SQL, return every merchant_id together with the order_id that represents that merchant’s first order for each calendar date.

Hints

Partition by merchant_id and order_date, order by order_time or order_id; use ROW_NUMBER() = 1.

First order per merchant per day

Using SQL, return every merchant_id together with the order_id that represents that merchant’s first order for each calendar date. Assume that in the absence of an order_time column, the earliest order is the one with the smallest order_id within each merchant_id and order_date.

Table Orders

columntypeconstraints
order_idINTEGERPRIMARY KEY, NOT NULL
merchant_idVARCHAR(10)NOT NULL
amountDECIMAL(10,2)NOT NULL
order_dateDATENOT NULL

Sample data:

amountmerchant_idorder_dateorder_id
120.5M012023-05-01101
75M022023-05-01102
90M012023-05-02103
250M032023-05-02104
110M012023-05-03105

Expected output

One row per merchant per calendar date, containing the first order_id of that day for that merchant. Since there is no order_time column, earliest is determined by the smallest order_id within each merchant_id and order_date.

merchant_idorder_dateorder_id
M012023-05-01101
M022023-05-01102
M012023-05-02103
M032023-05-02104
M012023-05-03105

Hints

  1. Use a window function with ROW_NUMBER() partitioned by merchant_id and order_date.
  2. Order the window by order_id to simulate the earliest order when no order_time is available.
  3. Filter to rows where ROW_NUMBER() = 1.