我正在使用案例语句来确定几个不同年龄组的 Count(*),但我需要获取每个年龄组的百分比,因为它与所有年龄组的总数有关。我知道这是一个新手问题,但我被卡住了。谢谢安迪
这是我尝试使用的代码。
WITH AgeGroups AS (
SELECT
CASE
WHEN DATEDIFF(YEAR, party.birthdate, GETDATE()) < 21 THEN 'Under 21'
WHEN DATEDIFF(YEAR, party.birthdate, GETDATE()) BETWEEN 21 AND 29 THEN '21 - 29'
WHEN DATEDIFF(YEAR, party.birthdate, GETDATE()) BETWEEN 30 AND 39 THEN '30 - 39'
WHEN DATEDIFF(YEAR, party.birthdate, GETDATE()) BETWEEN 40 AND 49 THEN '40 - 49'
WHEN DATEDIFF(YEAR, party.birthdate, GETDATE()) BETWEEN 50 AND 59 THEN '50 - 59'
WHEN DATEDIFF(YEAR, party.birthdate, GETDATE()) > 60 THEN '60 and Over'
ELSE 'Unkown'
END AS AgeGroup
FROM party
LEFT OUTER JOIN volunteer on partyID = volunteer.partyID
WHERE volunteer.swornDate BETWEEN @startDate AND @endDate)
SELECT AgeGroup, COUNT(*) AS AgeGroupCount, Convert(decimal(18,2),
(1.0*Count(*)/@Total * 100)) as percentage
FROM AgeGroups
GROUP BY AgeGroup
我正在尝试用所有年龄组的计数填充变量 @Total