Helpful Information
 
 
Category: MS SQL Development
Tring to find the Median

Hi,
I have written some code to find the Average score, only to find that I need to be looking for the Median score. I am not sure how I would go about getting the median instead of the average.

This is what I wrote. Does anyone have any suggestion on what would be the best way to change this code to reflect the median for each set of votes?

Thank you.


select distinct top 5 p.fldTitle 'Production Title',
count(v.idProduction) 'Number of Voters',
avg(v.fldTitleScore) 'Score',
v.idProduction 'Production ID',
m.fldOrganization 'Company',
p.fldContactPerson 'Contact Person',
p.fldContactPhone 'Contact Phone Number',
p.fldContactEmail 'Contact Email'
from wkProductioninfo p,
wkvote v,
wkProductionDate d,
wkMember m
where p.fldPlayMusical = 0
and p.fldWorldPremiere = 1
-- and p.fldSubmitting = 0
and p.fldsolo <> 1
and p.fldTour <> 1
and p.idUser <> '10000000'
and p.idUser <> '10000001'
and p.idUser = m.idUser
and p.idProduction = d.idProduction
and d.fldClosingDate < '09/01/03'
and p.idProduction = v.idProduction
and v.fldTitleScore > .00
group by v.idProduction, p.fldTitle, p.fldContactPerson, p.fldContactPhone, p.fldContactEmail, m.fldOrganization
having(count(v.idProduction) > 8 )
order by avg(v.fldTitleScore) desc
go

I don't think this is something you could do within a single query. You have to get the results, sort them and then the median calculation would be different depending on the numebr of values. A quick google came up with this: Calculating the Median Gets Simpler in SQL Server 2005 (http://www.sqlmag.com/article/tsql3/calculating-the-median-gets-simpler-in-sql-server-2005)

A quick google came up with this: Calculating the Median Gets Simpler in SQL Server 2005 (http://www.sqlmag.com/article/tsql3/calculating-the-median-gets-simpler-in-sql-server-2005)that article wasn't even written until three years after this thread was originally posted

it would be a very poor developer indeed who didn't know how to google, and instead hung around here for almost eight years waiting for an answer

please, acidedgeuk, leave dormant threads alone










privacy (GDPR)