繁体   English   中英

SQL为返回的年龄段创建存储过程

[英]SQL Creating a stored proc for returning age bands

我有一个名为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

创建一个包含您的乐队的表格:

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的另一个答案也是可用的,如果您可以/不会将另一个表添加到数据库中,这更合适。

一个简单的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

以下应该给出:

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

在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
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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM