我在下面的查询中提取了我所有农民的表中的所有年龄段,但是我需要按性别类型分类的数据。
WITH AgeData as
(
SELECT [sex],
[dob],
DATEDIFF(YEAR, [dob], GETDATE()) AS [AGE]
FROM dbo.Farmers
),
GroupAge AS
(
SELECT [sex],
[dob],
CASE
WHEN AGE < 24 THEN 'Under 24'
WHEN AGE BETWEEN 25 AND 30 THEN '25 - 30'
WHEN AGE BETWEEN 31 AND 40 THEN '31 - 40'
WHEN AGE BETWEEN 41 AND 50 THEN '41 - 50'
WHEN AGE > 50 THEN 'Over 50'
ELSE 'Invalid Birthdate'
END AS [Age Groups]
FROM AgeData
)
SELECT COUNT(*) AS [AgeGrpCount],[Age Groups]
FROM GroupAge
GROUP BY [Age Groups];
如果将其添加到代码中,我会得到我的男性性别类型:
WITH AgeData as
(
SELECT [sex],
[dob],
DATEDIFF(YEAR, [dob], GETDATE()) AS [AGE]
FROM dbo.Farmers
),
GroupAge AS
(
SELECT [sex],
[dob],
CASE
WHEN AGE < 24 THEN 'Under 24'
WHEN AGE BETWEEN 25 AND 30 THEN '25 - 30'
WHEN AGE BETWEEN 31 AND 40 THEN '31 - 40'
WHEN AGE BETWEEN 41 AND 50 THEN '41 - 50'
WHEN AGE > 50 THEN 'Over 50'
ELSE 'Invalid Birthdate'
END AS [Age Groups]
FROM AgeData
)
SELECT COUNT(*) AS [MaleAgeGrpCount],[Age Groups]
FROM GroupAge
Where sex = 1
GROUP BY [Age Groups];
但是我想同时使用[MaleAgeGrpCount]和[FemaleAgeGrpCount] Colum,而其中sex = 1是男性,而sex = 2是女性。
答案 0 :(得分:1)
使用条件聚合:
SELECT
[Age Groups],
COUNT(CASE WHEN sex = 1 THEN 1 END) AS [MaleAgeGrpCount],
COUNT(CASE WHEN sex = 2 THEN 1 END) AS [FemaleAgeGrpCount]
FROM GroupAge
GROUP BY [Age Groups];
这里的想法是使用单独的CASE
表达式来计算按年龄段汇总的男性和女性记录。