我想知道我是否可以在为每个DonorType组进行中位数计算时获得一些帮助。通过查询,我得到它只是对所有值进行中位数,而不是每个案例分组的值。我尝试了一些东西,环顾四周,但我被卡住了。
以下是我所拥有的:
SELECT DonorType = CASE WHEN [Criteria1] THEN 'AutoRecurring'
WHEN [Criteria2] THEN 'ManualRecurring'
ELSE 'NonRecurring' END,
COUNT(DISTINCT AccountNumber) AS TotalDonors, MIN(TotalDonationAmount) AS MinAmount,
MAX(TotalDonationAmount) AS MaxAmount, AVG(TotalDonationAmount) AS AvgAmount,
((SELECT MAX(TotalDonationAmount)
FROM (SELECT TOP 50 PERCENT TotalDonationAmount
FROM #TempDonors
ORDER BY TotalDonationAmount) AS BottomHalf)
+ (SELECT MIN(TotalDonationAmount)
FROM (SELECT TOP 50 PERCENT TotalDonationAmount
FROM #TempDonors
ORDER BY TotalDonationAmount DESC) AS TopHalf)) / 2 AS MedAmount
FROM #TempDonors
WHERE TotalDonationAmount > 0
GROUP BY CASE WHEN [Criteria1] THEN 'AutoRecurring'
WHEN [Criteria2] THEN 'ManualRecurring'
ELSE 'NonRecurring' END
非常感谢你的帮助。如果有另一个帖子问这个(我确定有,我只是不知道要搜索什么),一定只是发布链接 - 我提前道歉我的无能为力找到它。
小心!
答案 0 :(得分:0)
您需要将中位数计算与外部查询相关联。
它看起来像这样:
...
((SELECT MAX(TotalDonationAmount)
FROM (SELECT TOP 50 PERCENT TotalDonationAmount
FROM #TempDonors t1
WHERE CASE WHEN t.[Criteria1] THEN 'AutoRecurring'
WHEN t.[Criteria2] THEN 'ManualRecurring'
ELSE 'NonRecurring' END=CASE WHEN t1.[Criteria1] THEN 'AutoRecurring'
WHEN t1.[Criteria2] THEN 'ManualRecurring'
ELSE 'NonRecurring' END
ORDER BY TotalDonationAmount) AS BottomHalf)
+ (SELECT MIN(TotalDonationAmount)
FROM (SELECT TOP 50 PERCENT TotalDonationAmount
FROM #TempDonors t2
WHERE CASE WHEN t.[Criteria1] THEN 'AutoRecurring'
WHEN t.[Criteria2] THEN 'ManualRecurring'
ELSE 'NonRecurring' END=CASE WHEN t2.[Criteria1] THEN 'AutoRecurring'
WHEN t2.[Criteria2] THEN 'ManualRecurring'
ELSE 'NonRecurring' END
ORDER BY TotalDonationAmount DESC) AS TopHalf)) / 2 AS MedAmount
FROM #TempDonors
WHERE TotalDonationAmount > 0
GROUP BY CASE WHEN [Criteria1] THEN 'AutoRecurring'
WHEN [Criteria2] THEN 'ManualRecurring'
ELSE 'NonRecurring' END