Search code examples
sqlsql-serversql-server-2012averagemedian

Average and Median in one query in Sql Server 2012


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.

  1. To get average:

      SELECT category, avg(value) as Average
        FROM test
    GROUP BY category
    

     
     | category | value |
     +----------+-------+
     |    1     |   4   | 
     

  2. 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.


Solution

  • 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