Skip to content

44. Survey Scores by Question

Difficulty: Medium · Topics: Pivot, Unpivot & Rollup, Aggregations

survey has one row per respondent and one column per question: respondent, q1, q2, q3, each a score from 1 to 5, or null if the question was skipped.

Return one row per question with question ('q1', 'q2', 'q3'), answered (how many respondents answered it) and avg_score (average of the answers, rounded to 2 decimals). Skipped questions do not count as answers. Sort by question.

Row order matters for this problem. Your code is graded on 3 test cases, including hidden edge cases.

Sample data

survey

respondentq1q2q3
r154null
r23nullnull
r3452
r4null41

Expected output

questionansweredavg_score
q134
q234.33
q321.5

Hints

Hint 1Reshape wide to long first: survey.unpivot("respondent", ["q1", "q2", "q3"], "question", "score").
Hint 2count("score") and avg("score") both ignore nulls, which is exactly what "skipped" means here.
Hint 3A question nobody answered still appears, with 0 answers and a null average.

Learn the concepts

PySpark functions you'll practise

Related problems

Browse

Topics: Window Functions · Joins · Aggregations · Pivot, Unpivot & Rollup · Arrays · Null Handling · Conditional Logic · Dates · Filtering & Selection · Strings

Difficulty: Easy · Medium · Hard · PySpark interview roadmap · Learn · All problems