我在 SQL Server 中有下表:
-----------------------------
ID Age Gender
1 30 F
2 35 M
3 32 M
4 18 F
5 21 F
我需要做的是执行一个查询,它将给定范围内的记录分组并计算出现次数。结果需要稍后显示在直方图(条形图)中。我尝试了类似于以下的查询:
SELECT
count(CASE WHEN Age>= 10 AND Age < 20 THEN 1 END) AS '10 - 20',
count(CASE WHEN Age>= 21 AND Age < 30 THEN 1 END) AS '21 - 30',
count(CASE WHEN Age>= 31 AND Age < 35 THEN 1 END) AS '31 - 35',
count(CASE WHEN Age>= 36 AND Age < 40 THEN 1 END) AS '36 - 40',
FROM (SELECT Age FROM Attendees) AS AgeGroups
目前,这可以解决问题,但不考虑性别列。它将产生一行计算每个年龄组的频率:
10-20 21-30 31-35 36-40
0 22 21 13
如果考虑性别,则应针对每种性别显示两条记录。我需要看到类似的东西:
Gender 10-20 21-30 31-35 36-40
M 0 12 9 6
F 0 10 12 7
我应该如何解决这个问题?