Track Product Purchases
Beginner Mode
Scenario
You work for a retail store that tracks customer transactions and wants to understand repeat purchasing patterns.
Task
Write a Snowflake SQL query that:
- For each row in
{{ ref("transactions") }}, adds aprevious_productcolumn containing theproduct_idof the same customer's most recent prior transaction (ordered bydate), orNULLif there is no prior transaction - Adds a
date_and_productcolumn that concatenatesdateandprevious_productseparated by a space, substituting the string'None'whenprevious_productisNULL - Returns all six columns:
customer_id,product_id,quantity,date,previous_product,date_and_product
Schema
transactions
| Column | Type | Description |
|---|---|---|
| customer_id | String | Unique identifier for the customer |
| product_id | String | Unique identifier for the purchased product |
| quantity | Integer | Number of units purchased |
| date | String | Transaction date in YYYY-MM-DD format |
Example
transactions:
| customer_id | product_id | quantity | date |
|---|---|---|---|
| C1 | P10 | 3 | 2024-03-01 |
| C1 | P20 | 1 | 2024-03-15 |
| C2 | P30 | 2 | 2024-04-02 |
| C1 | P30 | 5 | 2024-04-10 |
| C3 | P10 | 4 | 2024-05-01 |
Expected Output:
| customer_id | product_id | quantity | date | previous_product | date_and_product |
|---|---|---|---|---|---|
| C1 | P10 | 3 | 2024-03-01 | NULL | 2024-03-01 None |
| C1 | P20 | 1 | 2024-03-15 | P10 | 2024-03-15 P10 |
| C1 | P30 | 5 | 2024-04-10 | P20 | 2024-04-10 P20 |
| C2 | P30 | 2 | 2024-04-02 | NULL | 2024-04-02 None |
| C3 | P10 | 4 | 2024-05-01 | NULL | 2024-05-01 None |
Note:
previous_productresets per customer. C2 and C3 each have only one transaction, so theirprevious_productisNULL. Thedate_and_productcolumn uses the literal string'None'whenprevious_productisNULL.
Code Environment
Sign in or try as guest to run your code.
Track
| Question | Difficulty | Company | Access |
|---|
Need more practice in this area? Explore more questions →
Microsoft