How to calculate median for selling_eur in this table?
id | listing_id | category | amount | original_eur | selling_eur | user_id | rounds_id | |
---|---|---|---|---|---|---|---|---|
0 | 10088 | m1-1579cd77-6863-469d-8798-9e1bef199d2f | Category 2 | 2 | nan | 350.11 | eu-central-1:6fcfad76-ef06-4ea6-9e14-9fa4a5d62b8f | 31 |
1 | 10089 | m1-2adfde90-de27-4048-aa3e-bc7e76c03b0c | Prime Seats | 4 | nan | 962.81 | eu-central-1:6fcfad76-ef06-4ea6-9e14-9fa4a5d62b8f | 28 |
2 | 10090 | m3-024c20ad-e21d-4bb3-966e-44c69e760b15 | Category 1 | 4 | 200 | 750 | eu-central-1:33d3dbe4-6414-4949-ae21-f2bc8819ae4d | 29 |
3 | 10091 | m1-c612ad6c-d000-4bb5-8dc4-55e3b49d54cd | Category 2 | 4 | 150 | 450 | eu-central-1:fe695442-13a6-42e6-a015-046415bf369d | 28 |
4 | 10092 | m1-cd449fb2-6134-428b-946a-fc8a7bec30e7 | Category 1 | 4 | nan | 647 | eu-central-1:b926a781-4fc0-4f71-bd0f-69b50b0be68d | 28 |
Calculate average is quite simle: sum( selling_eur * amount ) / sum ( amount).
But that about median?
Is it simple make arrays with prices, example for 1 row:
{350.1, 350.1}.
And make calculation for this values?
2
Answers
You could repeat your
selling_eur
exactlyamount
times in a subquery and feed that topercentile_cont()
. Demo at db<>fiddle:You can check what
percentile_cont()
saw and verify that’s the median:Here’s the one with window functions. The subquery adds to each row a range of positions according to the
selling_eur
order, and from that you can grab the value right below and right above the middle position (floor()
andceil()
filters), then divide their sum by two: demo