The measurements table records a numeric value for two groups, group_name = 'A' or 'B'. Compute each group's median and report which group has the higher median.
Do not use PERCENTILE_CONT or any other built-in median or percentile function; the query has to stay portable to engines such as MySQL 8 that lack them. Use ROW_NUMBER() and COUNT() to find the middle one or two ordered values of each group and average them.
Input Table(s)
measurements
| Column | Type | Meaning |
|---|
| group_name | VARCHAR(5) | Group of the measurement, 'A' or 'B' |
| value | DECIMAL(8,2) | The measured value |
There is no primary key. Each row is one measurement.
Output Contract
Exactly one row with these columns, in this order:
| Column | Definition |
|---|
| median_a | Median of group A, rounded to 2 decimals |
| median_b | Median of group B, rounded to 2 decimals |
| higher_group | 'A' or 'B' for the group with the larger median, 'tie' when the medians are equal |
The median of an odd number of values is the middle value; for an even number it is the average of the two middle values. higher_group compares the unrounded medians. The result is a single row, so no ordering applies.
Example
measurements
| group_name | value |
|---|
| A | 13.07 |
| B | 81.6 |
| B | 51.66 |
| A | 18.99 |
| B | 62.44 |
| A | 14.94 |
| B | 61.55 |
| B | 88.88 |
| A | 21.36 |
| A | 33.96 |
| B | 72.66 |
Expected result:
| median_a | median_b | higher_group |
|---|
| 18.99 | 67.55 | B |
Group A has 5 values, and its sorted middle value is 18.99. Group B has 6 values, and its two middle values are 62.44 and 72.66, which average to 67.55.
Constraints and Clarifications
-
group_name
is always
'A'
or
'B'
, and each group has at least one row.
-
value
is never NULL.
-
Duplicate values are allowed and each row counts.
-
PERCENTILE_CONT
,
PERCENTILE_DISC
,
MEDIAN
and similar built-ins are not allowed.