Write SQL Data Transformation Queries
TeslaData Engineer · Technical ScreenLast updated
This question tests the ability to handle window functions for running totals and conditional aggregation to transform raw manufacturing logs into formatted monthly production reports.
Problem Statement
You are given a table manufacturing_logs that tracks daily output for various assembly lines. You need to generate a summary report that shows the cumulative production for each line per month, while also calculating the percentage of production that was flagged as 'defective'.
Schema: manufacturing_logs
| Column | Type | Description |
|---|---|---|
log_id | INT | Unique identifier for the log entry |
line_id | INT | Identifier for the assembly line |
production_date | DATE | Date of production |
units_produced | INT | Total units manufactured on this date |
units_defective | INT | Units flagged as defective on this date |
Task
Write a SQL query to return a table with the following columns: line_id, month (in YYYY-MM format), total_produced, cumulative_monthly_production, and defect_rate.
total_produced: Total units produced by the line in that specific month.cumulative_monthly_production: The running total oftotal_producedfor that specificline_id, ordered by month.defect_rate: The ratio of total defective units to total produced units for that month, expressed as a percentage.
Example Input
| log_id | line_id | production_date | units_produced | units_defective |
|---|---|---|---|---|
| 1 | 101 | 2023-01-05 | 100 | 5 |
| 2 | 101 | 2023-01-20 | 200 | 10 |
| 3 | 101 | 2023-02-10 | 150 | 0 |
Example Output
| line_id | month | total_produced | cumulative_monthly_production | defect_rate |
|---|---|---|---|---|
| 101 | 2023-01 | 300 | 300 | 5.0 |
| 101 | 2023-02 | 150 | 450 | 0.0 |
Constraints
production_dateranges across multiple years.- Assume
units_produced> 0 for all rows.
Hints
Hint 1
First, group the data by line and month to calculate the base totals for each month before applying any window functions.
Hint 2
Use the `SUM(total_produced) OVER (PARTITION BY line_id ORDER BY month)` window function to calculate the running total.
Hint 3
Ensure you cast your division to a decimal/float type when calculating the defect rate to avoid integer division truncation.
Follow-up questions
- How would you modify this query to only include lines that had a defect rate exceeding 5% in any given month?
- If the table grew to billions of rows, what indexes would you suggest creating to optimize this aggregation?
- How would you handle a scenario where a `line_id` reports data in different time zones, potentially causing date shifts?
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.