我已经尝试了在特定列上计算中值的所有可能性,但继续从Excel中获取不同的值。
我正在研究SQL2008R2
这是我到目前为止所尝试的:
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
我在这里做了一件非常错的事吗?
我试过这个:Function to Calculate Median in Sql Server
谢谢
答案 0 :(得分:0)
所以我设法解决了这个问题。 问题是,出于某种原因,进行中位数计算得到的结果与Excels中位数函数的结果不同。
我创建了一个TEMP表并导入了我的UNION的结果,然后使用我的计算更新了Median列:
INSERT INTO #Temp
SELECT Entity,
BillPeriod,
((Cost) / (PatientDays)) * 100 AS Cost,
PatientDays,
0 AS Median
FROM GroupCTE
UNION
SELECT Entity,
BillPeriod,
((Cost) / (PatientDays)) * 100 AS Cost,
PatientDays,
0 AS Median
FROM RegionCTE
UNION
SELECT Entity,
BillPeriod,
((Cost) / (PatientDays)) * 100 AS Cost,
PatientDays,
0 AS Median
FROM InstitutionCTE
UNION
SELECT 'Median' as Entity,
BillPeriod,
0 AS Cost,
0 AS PatientDays,
0 AS Median
FROM InstitutionCTE
GROUP BY Entity, BillPeriod, PatientDays
UPDATE #Temp
SET Median = ((
((SELECT MAX(Cost) FROM
(SELECT TOP 50 PERCENT Cost FROM #Temp WHERE Cost <> 0 ORDER BY Cost ASC) AS BottomHalf)
+
(SELECT MIN(Cost) FROM
(SELECT TOP 50 PERCENT Cost FROM #Temp WHERE Cost <> 0 ORDER BY Cost DESC) AS TopHalf)
)) / 2)
SELECT * FROM #Temp
DROP TABLE #Temp