Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 934
Sergey Malyutin Avatar asked Oct 20 '25 16:10

Sergey Malyutin


1 Answers

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
like image 170
Kyle Hale Avatar answered Oct 22 '25 05:10

Kyle Hale