Using below query i am trying to get how many users are falling under which age group, for this i applied cross apply.
SELECT y.AgeDecade, COUNT(u.[UserId]) AS [TotalUsers]
FROM dbo.[User] u
CROSS APPLY (SELECT Age = (CONVERT(int, CONVERT(char(8), GETDATE(), 112)) - CONVERT(int, CONVERT(char(8), u.DateOfBirth, 112))) / 10000) x
CROSS APPLY (SELECT AgeDecade = CASE
WHEN x.Age <= 29 THEN 20
WHEN x.Age BETWEEN 30 AND 39 THEN 30
WHEN x.Age BETWEEN 40 AND 49 THEN 40
WHEN x.Age >= 50 THEN 50
ELSE NULL
END
) y
GROUP BY y.AgeDecade
Now besides [TotalUsers] i want to have another column [Percentage] which should give me the Percentage of that row across entire column.
I tried using 100 * COUNT(U.[UserId]) / SUM(U.[UserId]) but i see an erros stating UserId is not present in the select clause.. how do i get the percentage in this case ?