troubleshooting Question

Calculate median using SQL

Avatar of pansophy
pansophy asked on
Microsoft SQL Server
8 Comments1 Solution1573 ViewsLast Modified:
I am trying to calculate the median using the following formula which works. What I would like to do is replace the ' / 2 ' with ' * 0.5 ' so that I can then calculate percentiles rather than just the median.  

Problem is that no value is reported at all when I multiple by .5 rather than divide by 2.  The value returned is already a double so I'm not sure what the problem is.  

Any help would be appreciated.
SELECT      x.LPR AS median, COUNT(y.LPR) AS N
FROM          dbo.UpdatedAnalysis_filtered2 x CROSS JOIN
                        dbo.UpdatedAnalysis_filtered2 y
GROUP BY x.LPR
HAVING       (SUM(CASE WHEN y.LPR <= x.LPR THEN 1 ELSE 0 END) >= (COUNT(*) + 1) /2) AND (SUM(CASE WHEN y.LPR >= x.LPR THEN 1 ELSE 0 END) 
                        >= COUNT(*) /2 + 1)
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 8 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 8 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros