Table events has one row per user in an A/B test. variant says which arm the user was in ('A' is control, 'B' is treatment) and converted says whether the user converted (1 or 0). Write a query that returns a single row comparing the two variants: each variant's conversion rate, the absolute lift, and the relative lift as a percentage.
Input Table(s)
events
| Column | Type | Meaning |
|---|
| variant | VARCHAR(5) | Experiment arm: 'A' for control, 'B' for treatment |
| converted | SMALLINT | 1 if the user converted, 0 if not |
Each row is one user. The table has no user id column, so there is no declared key; every row counts as a distinct user.
Output Contract
Exactly one row with these columns, in this order:
| Column | Definition | Rounding |
|---|
| rate_control | conversions / users for variant 'A' | 4 decimals |
| rate_treatment | conversions / users for variant 'B' | 4 decimals |
| abs_lift | rate_treatment - rate_control | 4 decimals |
| rel_lift_pct | abs_lift / rate_control * 100 | 2 decimals |
Compute abs_lift and rel_lift_pct from the unrounded rates and round only the final values. The result has a single row, so no ordering is needed.
Example
Input events:
| variant | converted |
|---|
| B | 0 |
| B | 0 |
| B | 0 |
| A | 0 |
| A | 1 |
| B | 0 |
| B | 1 |
| B | 0 |
| A | 0 |
| B | 1 |
| A | 0 |
| A | 0 |
| A | 0 |
| B | 1 |
| B | 0 |
| A | 0 |
| A | 1 |
| A | 0 |
Expected result:
| rate_control | rate_treatment | abs_lift | rel_lift_pct |
|---|
| 0.2222 | 0.3333 | 0.1111 | 50.00 |
Control has 9 users and 2 conversions, so its rate is 2/9 = 0.2222. Treatment has 9 users and 3 conversions, so its rate is 3/9 = 0.3333. The absolute lift is 1/9 = 0.1111, and the relative lift is (1/9) / (2/9) * 100 = 50.00.
Constraints and Clarifications
-
variant
only takes the values
'A'
and
'B'
, and each variant has at least one row.
-
converted
is never NULL and is always 0 or 1.
-
Every row is a different user, so there is nothing to deduplicate.
-
If the control conversion rate is 0, the relative lift is undefined. Return NULL for
rel_lift_pct
in that case; the query must not fail with a division-by-zero error.
-
The rates must be decimal values. Dividing one integer count by another truncates to 0 in PostgreSQL.