我有一个名为Person的表,其中包含一个名为PersonAge的字段。我需要按年龄段分组年龄,即'12及以下','13 -17','18 -25','25及以上',并使用存储过程返回此结果集。
理想情况下,我需要返回2个字段,'Age Band','Total'就像这样
Age band Total 12 and under 5 13 - 17 8 18 - 25 7 25 and over 10
答案 0 :(得分:13)
创建一个包含乐队的表格:
CREATE TABLE agebands
(
id INT NOT NULL PRIMARY KEY,
lower_bound INT NOT NULL,
upper_bound INT NOT NULL
)
CREATE INDEX IDX_agebands_bounds ON (lower_bound, upper_bound)
然后用您的数据填充它:
INSERT INTO agebands VALUES (1, 0, 12)
INSERT INTO agebands VALUES (2, 13, 17)
INSERT INTO agebands VALUES (3, 18, 24)
INSERT INTO agebands VALUES (4, 25, 199)
然后加入它:
SELECT
lower_bound, upper_bound,
COUNT(*) AS number_of_people
FROM
persons
INNER JOIN agebands
ON person_age BETWEEN lower_bound AND upper_bound
GROUP BY
lower_bound, upper_bound
ORDER BY
lower_bound
这允许灵活地调整频带。当然,这里使用UNION的另一个答案也是可用的,如果您可以/不会将另一个表添加到数据库中,这更合适。
答案 1 :(得分:4)
一个简单的UNION就足够了。
SELECT [Ageband] = '12 and under', COUNT(*)
FROM dbo.Person
WHERE PersonAge <= 12
UNION ALL SELECT '13-17', COUNT(*)
FROM dbo.Person
WHERE PersonAge BETWEEN 13 AND 17
UNION ALL SELECT '18-25', COUNT(*)
FROM dbo.Person
WHERE PersonAge BETWEEN 18 AND 25
UNION ALL SELECT '26 and over', COUNT(*)
FROM dbo.Person
WHERE PersonAge >= 26
答案 2 :(得分:2)
以下内容应该给出:
select count(*), person_age
from (
select (case
when age between 0 and 12 then '12 and under'
when age between 13 and 17 then '13-17'
when age between 18 and 25 then '18-15'
else 'Above 25'
end) as 'person_age'
from person)
group by person_age
答案 3 :(得分:1)
在SQL中,您无法按列别名进行分组。您需要像这样重复案例陈述。
select count(*),
case
when aged between 0 and 12 then '12 and under'
when aged between 13 and 17 then '13-17'
when aged between 18 and 25 then '18-15'
else 'Above 25' end
from person
group by
case
when aged between 0 and 12 then '12 and under'
when aged between 13 and 17 then '13-17'
when aged between 18 and 25 then '18-15'
else 'Above 25'
end
答案 4 :(得分:0)
declare @tempT table(age int)
declare @temp2 table(age2 varchar(15))
insert into @tempT(age) values(1)
insert into @tempT(age) values(2)
insert into @tempT(age) values(3)
insert into @tempT(age) values(4)
insert into @tempT(age) values(5)
insert into @tempT(age) values(6)
insert into @tempT(age) values(7)
insert into @tempT(age) values(8)
insert into @tempT(age) values(9)
insert into @tempT(age) values(10)
insert into @tempT(age) values(11)
insert into @Temp2
select case
when age < 3 then '<3'
when age >= 3 and age < 5 then '>= 3 and < 5'
when age >= 5 then '>=5'
end
from @tempT
select count(*), age2 from @Temp2
GROUP BY age2