I have the following data in my table:
SELECT category, value FROM test
| category | value | +----------+-------+ | 1 | 1 | | 1 | 3 | | 1 | 4 | | 1 | 8 |
Right now I am using two separate queries.
To get average:
SELECT category, avg(value) as Average
FROM test
GROUP BY category
| category | value | +----------+-------+ | 1 | 4 |
To get median:
SELECT DISTINCT category,
PERCENTILE_CONT(0.5)
WITHIN GROUP (ORDER BY value)
OVER (partition BY category) AS Median
FROM test
| category | value | +----------+-------+ | 1 | 3.5 |
Is there any way to merge them in one query?
Note: I know that I can also get median with two subqueries, but I prefer to use PERCENTILE_CONT function to get it.
AVG is also a windowed function:
select
distinct
category,
avg(value) over (partition by category) as average,
PERCENTILE_CONT(0.5)
WITHIN GROUP (ORDER BY value)
OVER (partition BY category) AS Median
from test