Back to questions
This is the same question as problem #13 in the SQL Chapter of Ace the Data Science Interview!
Assume you are given the table on Walmart user transactions. Based on a user's most recent transaction date, write a query to obtain the users and the number of products bought.
Output the user's most recent transaction date, user ID and the number of products sorted by the transaction date in chronological order.
P.S. As of 10 Nov 2022, the official solution was changed from output of the transaction date, number of users and number of products to the current output.
The dataset you are querying against may have different input & output - this is just an example!
First, we obtain the latest transaction date for each user using a window function by partitioning by user and ordering by transaction date in descending order.
Using the above query, we convert it into a common table expression (CTE) with a statement or a subquery. In this example, we are using CTE.
Subsequently, we filter for records where equals 1 indicating the latest transaction date and declare the transaction date and user ID in the statement.
We also include a count of product IDs as the number of products and order the results by transaction date.
Solution #1: Using CTE
Solution #2: Using Subquery