如何使用select语句设置变量并在case语句中使用它

时间:2012-04-18 03:01:21

标签: tsql

我使用案例陈述来确定几个不同年龄组的计数(*),但我需要得到每个年龄组的百分比,因为它与所有年龄组的总数有关。 我知道这是一个新手问题,但我被困住了。 谢谢 安迪

以下是我尝试使用的代码。

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

1 个答案:

答案 0 :(得分:0)

根据您的问题,您不清楚是否要填充@Total或生成查询输出。

如果是晚些时候,那么这可能适合你。

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(*)/b.totcnt * 100)) as percentage 

FROM AgeGroups a,
(select COUNT(*) AS totcnt from AgeGroups) b

GROUP BY a.AgeGroup