Solve SQL and PySpark Data Tasks
Point72Data Engineer · Online AssessmentLast updated
This question tests your ability to handle data cleaning, filtering, and aggregation using both SQL and PySpark syntax on a transaction dataset.
Scenario
You are given a dataset containing financial transactions. Each row represents a trade with the following columns: trade_id (string), account_id (string), amount (float), trade_date (timestamp), and status (string: 'COMPLETED', 'PENDING', 'FAILED').
Tasks
-
Write a SQL query to calculate the total transaction amount per
account_idfor 'COMPLETED' trades, filtered to include only transactions that occurred in the year 2023. Order the results by total amount in descending order. -
Using PySpark, perform the same calculation as above. Additionally, remove any duplicate
trade_identries before performing the aggregation. Ensure the result is returned as a Spark DataFrame.
Data Assumptions
- Input:
tradestable. - Constraints: The dataset can contain duplicate
trade_identries that must be handled in the PySpark version.
Example
Input trades table:
| trade_id | account_id | amount | trade_date | status |
|---|---|---|---|---|
| 1 | A1 | 100.0 | 2023-01-15 | COMPLETED |
| 1 | A1 | 100.0 | 2023-01-15 | COMPLETED |
| 2 | A1 | 50.0 | 2023-02-10 | COMPLETED |
| 3 | A2 | 200.0 | 2022-12-31 | COMPLETED |
Output:
| account_id | total_amount |
|---|---|
| A1 | 150.0 |
Explanation: Duplicate trade_id 1 is removed. Trade 3 is ignored due to the date filter (2022).
Hints
Hint 1
In SQL, use the YEAR() function or a date range filter on the trade_date column.
Hint 2
In PySpark, use .dropDuplicates(['trade_id']) to clean the data before applying .groupBy().
Hint 3
Remember that PySpark aggregation functions like sum() must be imported from pyspark.sql.functions.
Follow-up questions
- How would you handle missing values (NULLs) in the 'amount' column before performing the aggregation?
- If the 'trades' table were partitioned by 'trade_date', how would that change your query strategy for better performance?
- How does a broadcast join work in Spark, and in what scenario would you suggest using it?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.