I have tried all possibilities in working out the Median value on a specific column but keep on getting a different value from Excel.
I am working on SQL2008R2
This is what I have tried so far :
SELECT Entity,
BillPeriod,
Cost,
PatientDays,
0 AS Median
FROM GroupCTE
UNION
SELECT Entity,
BillPeriod,
Cost,
PatientDays,
0 AS Median
FROM RegionCTE
UNION
SELECT Entity,
BillPeriod,
Cost,
PatientDays,
0 AS Median
FROM InstitutionCTE
Union
SELECT 'Median' as Entity,
BillPeriod,
0 as Cost,
0 as PatientDays,
(((
(SELECT MAX(Cost) FROM
(SELECT TOP 50 PERCENT Cost FROM InstitutionCTE WHERE Cost <> 0 ORDER BY Cost ASC) AS BottomHalf)
+
(SELECT MIN(Cost) FROM
(SELECT TOP 50 PERCENT Cost FROM InstitutionCTE WHERE Cost <> 0 ORDER BY Cost DESC) AS TopHalf)
)) / 2) AS Median
Am I doing something terribly wrong here?
I tried this : Function to Calculate Median in Sql Server
Thank you