For every sale, return sale_id, region, amount, amount_rank, region_avg and region_total. All three metrics must share one named WINDOW clause partitioned by region and ordered by amount DESC.
Input Table(s)
Table sales (primary key sale_id):
| Column | Type | Meaning |
|---|
| sale_id | INT | Identifier of the sale; unique |
| region | VARCHAR(50) | Region of the sale; may be NULL |
| amount | INT | Sale amount; a non-negative integer |
Output Contract
One row per sale, with these columns in this order:
| Column | Definition |
|---|
| sale_id | The sale's sale_id |
| region | The sale's region |
| amount | The sale's amount |
| amount_rank | RANK() of the sale within its region by amount descending; ties share a rank and the next rank skips |
| region_avg | Average amount of the region's sales from the highest amount down to the current row, rounded to 2 decimals |
| region_total | Sum of amount over the same rows as region_avg |
Use the default RANGE frame, so tied rows are all included in each other's cumulative aggregates. Order the result by region ascending with NULL last, then amount descending, then sale_id ascending.
Example
sales:
| sale_id | region | amount |
|---|
| 1 | East | 100 |
| 2 | East | 300 |
| 3 | East | 200 |
| 4 | West | 500 |
Expected output:
| sale_id | region | amount | amount_rank | region_avg | region_total |
|---|
| 2 | East | 300 | 1 | 300.00 | 300 |
| 3 | East | 200 | 2 | 250.00 | 500 |
| 1 | East | 100 | 3 | 200.00 | 600 |
| 4 | West | 500 | 1 | 500.00 | 500 |
In East, ranked by amount descending, the order is 300 (rank 1), 200 (rank 2), 100 (rank 3), and the average and total accumulate down that order. West has a single row with rank 1.
A second input with a tie and a NULL region:
| sale_id | region | amount |
|---|
| 5 | North | 50 |
| 6 | North | 90 |
| 7 | North | 50 |
| 8 | NULL | 40 |
Expected output:
| sale_id | region | amount | amount_rank | region_avg | region_total |
|---|
| 6 | North | 90 | 1 | 90.00 | 90 |
| 5 | North | 50 | 2 | 63.33 | 190 |
| 7 | North | 50 | 2 | 63.33 | 190 |
| 8 | NULL | 40 | 1 | 40.00 | 40 |
Sales 5 and 7 tie at 50, so both get rank 2 and both frames cover all three North rows: 90 + 50 + 50 = 190, and 190 / 3 rounds to 63.33. Sale 8 is alone in the NULL-region group and sorts last.
Constraints and Clarifications
-
The table has 1 to 10,000 rows.
-
amount
is a non-negative integer.
-
sale_id
is unique.
-
region
may be NULL. All rows with a NULL region form one group and are ranked and aggregated together.
-
Tied amounts within a region share a rank and share the same
region_avg
and
region_total
.