ab_events has one row per visitor in a two-variant conversion test, with the variant the visitor saw and whether they converted. Compute the Yates continuity-corrected chi-square statistic for the 2x2 variant-by-outcome table and return one row with chi_square_yates rounded to 4 decimals.
Use this formula, where a,b,c,d are the cell counts, r1,r2,k1,k2 the row and column totals and n the grand total:
χYates2=r1r2k1k2n(max(∣ad−bc∣−n/2, 0))2
| converted | not_converted | row total |
|---|
| control | a | b | r1 = a + b |
| treatment | c | d | r2 = c + d |
| column total | k1 = a + c | k2 = b + d | n |
Input Table(s)
ab_events
| Column | Type | Meaning |
|---|
| variant | VARCHAR(20) | The arm the visitor saw: 'control' or 'treatment' |
| outcome | VARCHAR(20) | 'converted' or 'not_converted' |
There is no primary key. Each row is one visitor, so two identical rows are two different visitors.
Output Contract
Exactly one row with one column:
| Column | Type | Meaning |
|---|
| chi_square_yates | NUMERIC | The continuity-corrected statistic, rounded to 4 decimal places |
The result always has one row, so no ordering is needed.
Example
Input ab_events (17 rows):
| variant | outcome |
|---|
| control | not_converted |
| control | converted |
| treatment | not_converted |
| treatment | converted |
| treatment | converted |
| treatment | not_converted |
| control | not_converted |
| treatment | not_converted |
| control | not_converted |
| control | not_converted |
| control | not_converted |
| treatment | converted |
| treatment | converted |
| control | not_converted |
| control | converted |
| control | converted |
| treatment | converted |
Expected output:
Control has 3 converted and 6 not converted visitors, and treatment has 5 and 3, so n=17, the row totals are 9 and 8 and the column totals are 8 and 9. Then ∣ad−bc∣=∣9−30∣=21, the correction removes 8.5, and
χYates2=9⋅8⋅8⋅917⋅12.52=51842656.25≈0.5124.
Constraints and Clarifications
-
variant
is always
'control'
or
'treatment'
, and
outcome
is always
'converted'
or
'not_converted'
. Neither column contains NULLs.
-
Both variants and both outcomes appear at least once, so every row and column total is positive and the statistic is defined.
-
n/2
is exact division: for
n=17
it is 8.5.
-
Keep the clamp at 0 exactly as written. When
∣ad−bc∣
is less than
n/2
, the statistic is 0.
-
The query should stay correct at production sizes (hundreds of thousands of visitors per variant), not only on the small example.