Cleaning Account Data in R and Selecting Top Half of Students in SQL
SQL & DataModel answerLast updated
Clean a customer CSV with ordered null-handling rules and compute two averages in tidyverse R, then write one MySQL 8 query returning the top half of students by average grade.
This problem has two independent parts. Both test whether you can apply data-quality rules in the right order and rank rows deterministically.
Part A: Account metrics in R (tidyverse)
You are given a CSV of subscription accounts with these columns:
| Column | Type | Notes |
|---|---|---|
id | INT | may be NULL or blank |
signup_date | date (YYYY-MM-DD) | |
last_active_date | date (YYYY-MM-DD) | |
churned | 0 / 1 / NULL | |
pay | decimal / NULL |
Apply these rules:
- Remove rows whose
idis NULL or blank. - A NULL
paybecomes0. - If
churnedis NULL andpay > 0, setchurned = 0(the account is still active). active_daysis the number of days fromsignup_datetolast_active_date. Iflast_active_datecomes beforesignup_date, use0.- For accounts with
churned = 1,last_active_dateis the churn date.
Compute, on the cleaned data:
- (a) the average
active_daysover all remaining accounts; - (b) the average
payover accounts withchurned = 1.
Round both values to 2 decimals. Use idiomatic tidyverse code and briefly explain how your code enforces each rule.
Sample input:
| id | signup_date | last_active_date | churned | pay |
|---|---|---|---|---|
| 1 | 2025-01-10 | 2025-03-05 | 1 | 99 |
| 2 | 2025-02-01 | 2025-02-20 | NULL | 15 |
| 3 | 2025-01-15 | 2025-01-18 | 0 | NULL |
| NULL | 2025-02-10 | 2025-02-12 | 1 | 50 |
| 4 | 2025-02-11 | 2025-02-05 | 1 | 25 |
Part B: Top half of students in MySQL 8.0
Schema:
Teachers(id PK, name, classroom)Students(id PK, name, primary_teacher_id FK -> Teachers.id)Assignments(id PK, teacher_id FK -> Teachers.id)Grades(student_id FK -> Students.id, assignment_id FK -> Assignments.id, grade DECIMAL(4,1), PK(student_id, assignment_id))
Write one query that:
- computes each student's
avg_scoreover all their grades; - excludes students with no completed (graded) assignments;
- keeps only the top
CEIL(N/2)students by average, whereNis the number of students with at least one grade; ties are broken bystudent_idascending; - returns
student_id,name,avg_score(rounded to 1 decimal) and a dense rank over the selected students ordered byavg_score DESC, student_id ASC; - keeps working correctly as students and grades are added, so nothing may be hard-coded.
Sample data:
Students
| id | name | primary_teacher_id |
|---|---|---|
| 1 | Bobby | 4 |
| 2 | Susie | 8 |
| 3 | Deborah | 8 |
| 9 | Bruce | NULL |
Grades
| student_id | assignment_id | grade |
|---|---|---|
| 1 | 1 | 100.0 |
| 1 | 2 | 50.0 |
| 2 | 1 | 100.0 |
| 2 | 2 | 100.0 |
| 3 | 1 | 40.0 |
| 3 | 2 | 8.0 |
| 9 | 1 | 65.0 |
| 9 | 2 | 65.0 |
(Teachers has rows 4 / Mr. Feeny / 301 and 8 / Mr. Cooper / 260; Assignments has rows 1 -> teacher 4 and 2 -> teacher 8.)
Hints
Hint 1
In Part A, rule order matters: the `churned` imputation depends on `pay` already being filled in, so impute `pay` first. Read `id` as text so whitespace-only values can be detected before converting to integer.
Hint 2
For metric (b), `churned == 1` yields NA for rows with an unknown status, which breaks subsetting. Use `churned %in% 1` or `which()` so unknown status counts as not churned.
Hint 3
In Part B, you cannot filter on a window function in WHERE, so compute `ROW_NUMBER()` and `COUNT(*) OVER ()` in a CTE and filter in the outer query. Do not join `Teachers`, or students with a NULL `primary_teacher_id` disappear.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part A: Cleaning and metrics in R
Approach
Treat the cleaning as a pipeline in which each rule is one visible step, so it is easy to audit. The order is:
- Parse NULL-like strings as
NA. - Drop rows with a missing or blank
id. - Fill
pay. - Fill
churned, using the already-filledpay. - Derive
active_daysandchurn_date. - Aggregate.
library(dplyr)
library(readr)
prepare_accounts <- function(path) {
read_csv(
path,
na = c("", "NULL", "NA"),
col_types = cols(
id = col_character(), # text, so " " can be detected
signup_date = col_date("%Y-%m-%d"),
last_active_date = col_date("%Y-%m-%d"),
churned = col_integer(),
pay = col_double()
)
) %>%
mutate(id = na_if(trimws(id), "")) %>%
filter(!is.na(id)) %>% # rule 1
mutate(
id = as.integer(id),
pay = coalesce(pay, 0), # rule 2
churned = if_else(is.na(churned) & pay > 0, 0L, churned), # rule 3
active_days = pmax(as.integer(last_active_date - signup_date), 0L), # rule 4
churn_date = if_else(churned %in% 1L, last_active_date,
as.Date(NA)) # rule 5
)
}
summarise_accounts <- function(df) {
df %>%
summarise(
avg_active_days = round(mean(active_days, na.rm = TRUE), 2),
avg_pay_churned = round(mean(pay[churned %in% 1L]), 2)
)
}
prepare_accounts("customers.csv") %>% summarise_accounts()
How each rule is enforced
- Rule 1:
idis read as character, trimmed, and empty strings becomeNA;filter(!is.na(id))then removes them. Parsing straight to integer could leave whitespace-only ids in an awkward state. - Rule 2:
coalesce(pay, 0). - Rule 3: runs after rule 2, so
pay > 0is neverNA. A NULLchurnedwithpay = 0staysNA, since the spec gives no rule for that case and we should not invent one. - Rule 4: subtracting two
Datevalues gives days, matchingDATEDIFF(last, signup).pmax(..., 0L)floors negatives at zero. - Rule 5:
churn_dateis set only whenchurnedis 1. It does not change either metric, but it makes the definition explicit. - Metric (b):
churned %in% 1LisFALSEforNA, so unknown-status rows are excluded cleanly.
Worked example
| id | active_days | churned | pay |
|---|---|---|---|
| 1 | 54 | 1 | 99 |
| 2 | 19 | 0 (rule 3) | 15 |
| 3 | 3 | 0 | 0 (rule 2) |
| 4 | 0 (floored from -6) | 1 | 25 |
The NULL-id row is dropped.
avg_active_days = (54 + 19 + 3 + 0) / 4 = 19.00avg_pay_churned = (99 + 25) / 2 = 62.00
Edge cases to mention
- Missing dates give
NAinactive_days. Withna.rm = TRUEthey are skipped; state that assumption, or drop those rows earlier. - With no churned accounts,
mean(numeric(0))isNaN. Convert it toNAif downstream code expects that. - R's
round()can round exact ties to even, so usesprintf("%.2f", x)for display only. - Malformed date strings become
NAwith a warning; inspect them withproblems().
Complexity is O(n) time and a single pass over the data.
Part B: Top half of students in MySQL
Approach
- Aggregate one row per student. An inner join to
Gradesautomatically removes students with no grades, so they are not counted in N. Filteringgrade IS NOT NULLensures only real grades count as "completed". - Rank and count in a CTE:
ROW_NUMBER()over(avg DESC, student_id ASC)gives a strict ordering, andCOUNT(*) OVER ()gives N without hard-coding or a second query. - Filter and present: keep
rn <= CEIL(N/2), round only for output, and compute the requestedDENSE_RANK.
WITH per_student AS (
SELECT s.id AS student_id,
s.name AS name,
AVG(g.grade) AS avg_raw
FROM Students s
JOIN Grades g ON g.student_id = s.id
WHERE g.grade IS NOT NULL
GROUP BY s.id, s.name
),
numbered AS (
SELECT student_id,
name,
avg_raw,
ROW_NUMBER() OVER (ORDER BY avg_raw DESC, student_id ASC) AS rn,
COUNT(*) OVER () AS n_total
FROM per_student
)
SELECT student_id,
name,
ROUND(avg_raw, 1) AS avg_score,
DENSE_RANK() OVER (ORDER BY avg_raw DESC, student_id ASC) AS score_rank
FROM numbered
WHERE rn <= CEIL(n_total / 2)
ORDER BY score_rank;
Why it is correct
- No Teachers join. Bruce has
primary_teacher_id = NULL; an inner join toTeacherswould silently drop him and shrink N. Nothing in the requirements needs that table. - Exact cutoff.
ROW_NUMBERwith thestudent_idtie-breaker yields exactlyCEIL(N/2)rows.RANKor a threshold on the average could admit extra tied students. In MySQL/is decimal division, soCEIL(5/2) = 3as intended. - Rank on unrounded values. Rounding first could make 87.44 and 87.36 tie at 87.4 and change the order. Round only in the final SELECT.
- Window functions run after WHERE. That is why the filter on
rnsits in the outer query, after the CTE. - Scales with data. N and the cutoff are recomputed on every run.
Worked example
Averages: student 1 = 75.0, student 2 = 100.0, student 3 = 24.0, student 9 = 65.0. So N = 4 and the cutoff is 2.
| student_id | name | avg_score | score_rank |
|---|---|---|---|
| 2 | Susie | 100.0 | 1 |
| 1 | Bobby | 75.0 | 2 |
Trade-offs and common mistakes
- Because
student_idis unique,DENSE_RANK() OVER (ORDER BY avg DESC, student_id ASC)always equals the row number. If the intent is for tied averages to share a rank, order byavg_raw DESConly. Raise this ambiguity with the interviewer rather than guessing. - Using
LEFT JOINfrom Students would include ungraded students in N and give them a NULL average. - Using
LIMIT CEIL(...)with a subquery is not allowed in MySQL; the window approach avoids it. - Complexity is one aggregation plus one sort, O(n log n) in the number of graded students, with an index on
Grades(student_id)helping the join.