Problems / Two-Dimensional Crosstab / Editorial
A crosstab (contingency table) is a pivot on counts: rows are one categorical dimension (plan), columns are the other (billing_period).
plan
billing_period
GROUP BY plan
COUNT(CASE WHEN billing_period = 'monthly' THEN 1 END)
COUNT(*)
In PySpark: F.count(F.when(F.col("billing_period") == "monthly", True)) per period and F.count(F.lit(1)) for the total.
F.count(F.when(F.col("billing_period") == "monthly", True))
F.count(F.lit(1))
SUM(CASE ... THEN amount END) pivots *values*; COUNT(CASE ... THEN 1 END) pivots *frequencies* — and COUNT's ignore-NULLs semantics is exactly what turns "no matching rows" into the 0 a crosstab requires (SUM with no ELSE would give NULL instead). The starter plan, which has only monthly subscriptions, is the proof in this dataset: its annual_count must be 0.
SUM(CASE ... THEN amount END)
COUNT(CASE ... THEN 1 END)
starter
annual_count
Solve Two-Dimensional Crosstab yourself →