Problems / Recode and Pivot Ratings / Editorial
Two independent transformations, cleanest done in two layers:
score <= 2
score = 3
withColumn
GROUP BY survey_id
COUNT(CASE WHEN segment = 'detractor' THEN 1 END)
Recode-then-pivot beats stuffing the range checks into every aggregate (COUNT(CASE WHEN score <= 2 ...) repeated three times): the business rule — what makes a detractor — lives in exactly one place, and the pivot layer stays mechanical. When the segment boundaries change, only the CASE changes. The boundary scores are where wrong solutions die: 2 is still a detractor, 3 is passive (not a detractor, not a promoter), and 4 is already a promoter.
COUNT(CASE WHEN score <= 2 ...)
Solve Recode and Pivot Ratings yourself →