我在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
我该如何处理这个问题?
答案 0 :(得分:31)
只需将Gender
列添加到SELECT
,然后执行GROUP BY
。
SELECT
Gender,
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 Attendees AS AgeGroups
GROUP BY Gender
答案 1 :(得分:0)
上面的示例不包括值20、30、35和40。 这只猫有不只一种方法,这是一种:
SELECT
Gender,
count(CASE WHEN Age> 9 AND Age <= 20 THEN 1 END) AS [10 - 20],
count(CASE WHEN Age> 20 AND Age <= 30 THEN 1 END) AS [21 - 30],
count(CASE WHEN Age> 30 AND Age <= 35 THEN 1 END) AS [31 - 35],
count(CASE WHEN Age> 35 AND Age <= 40 THEN 1 END) AS [36 - 40]
FROM Attendees AS AgeGroups
GROUP BY Gender
答案 2 :(得分:0)
我最近遇到了一个类似的问题,我需要查看几个变量而不是一个,而我的解决方案是使用临时表。
CREATE TABLE #bin (
startRange int,
endRange int,
agelabel varchar(10)
);
GO
INSERT INTO #bin (startRange, endRange, mylabel) VALUES (10, 20, '10-20')
INSERT INTO #bin (startRange, endRange, mylabel) VALUES (21, 30, '21-30')
INSERT INTO #bin (startRange, endRange, mylabel) VALUES (31, 35, '31-35')
INSERT INTO #bin (startRange, endRange, mylabel) VALUES (36, 40, '36-40')
GO
SELECT
b.agelabel as ageBracket,
a.Gender,
count(a.Gender) as total
FROM
Attendees a
INNER JOIN
#bin b on (a.Age >= b.startRange and a.Age <= b.EndRange)
GROUP BY
b.agelabel, a.Gender
DROP TABLE #bin
GO
或者,也许是更好的解决方案,
With table1 as
(
SELECT
CASE
WHEN Age >= 10 and Age <= 20 then '10-20'
WHEN Age > 20 and Age <= 30 then '21-30'
WHEN Age > 30 and Age <= 35 then '31-35'
WHEN Age > 35 and Age <= 40 then '36-40'
ELSE 'NA'
End as ageBracket,
Gender
FROM
Attendees
)
SELECT
ageBracket,
Gender,
Count(Gender),
FROM
table1
GROUP BY
ageBracket, Gender
结果将是:
AgeBracket Gender Total
10-20 M 0
10-20 F 0
21-30 M 12
21-30 F 10
31-35 M 9
31-35 F 12
36-40 M 6
36-40 F 7
您可以使用第一个选择语句来收集您选择的所有数据,而使用第二个查询来执行任何必要的计算。
我认为这些解决方案可能对您的问题有些大材小用,但是由于这是我发现的有关装箱的唯一问题,希望对其他人有用!