0

I have a number of select statements which calculate fields such as sums, division and also averages. However I am now needing to include a median based on the query, as well as a mean(avg). The table contains 50,000 rows in the MSSQL database, so in the same query return I need to have the results return for each line.

I know there is not a Median formula in SQl, well not that I am aware of. I am using SQL 2012. So if anyone has an idea, I would welcome your thoughts, as I can not be the only person to come up against this.

Example would be something like this

Select 
     Round (AVG ([LENGTH]),2) as Length_X,
     Round (Median ([LENGTH]),2) as Length_median,

I understand Median is not an accepted sql statement, so just for demo purposes to get my point across

Cheers

Processit
  • 55
  • 1
  • 10

1 Answers1

1

If you have numeric data, then there is a "median" function. It is just spelled differently:

select percentile_cont(0.5) within group (order by ??) over ()

or

select percentile_disc(0.5) within group (order by ??) over ()

(The difference between the two is subtle and probably doesn't matter for most purposes.)

It is, unfortunately, not an aggregation function, so it is often used in a subquery.

Gordon Linoff
  • 1,122,135
  • 50
  • 484
  • 624