sqlserver按年龄段统计人数

已知:现有一张职工信息表,职工编号,职工姓名,职工生日,公司编码

求:统计根据输入的公司编码统计改公司各年龄段的人数 年龄段分别为 30岁以下,31-35,36-45,46-55,56以上;

 

初始化数据如下;

CREATE TABLE lzy_test(
 [id] [int] NOT NULL,
 [name] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
 [birthday] [datetime] NULL,
 [school_code] [int] NULL,
 CONSTRAINT [PK_lzy_test] PRIMARY KEY CLUSTERED
)


INSERT INTO lzy_test (id,name,birthday,school_code) VALUES (1,'name1',{ts '2010-01-01 00:00:00.'},1)
GO
INSERT INTO lzy_test (id,name,birthday,school_code) VALUES (2,'name2',{ts '1989-01-02 00:00:00.'},1)
GO
INSERT INTO lzy_test (id,name,birthday,school_code) VALUES (3,'name3',{ts '1978-02-07 00:00:00.'},1)
GO
INSERT INTO lzy_test (id,name,birthday,school_code) VALUES (4,'name4',{ts '1971-01-08 00:00:00.'},1)
GO
INSERT INTO lzy_test (id,name,birthday,school_code) VALUES (5,'name5',{ts '1990-09-09 00:00:00.'},1)
GO
INSERT INTO lzy_test (id,name,birthday,school_code) VALUES (9,'name9',{ts '1981-01-08 00:00:00.'},1)
GO
INSERT INTO lzy_test (id,name,birthday,school_code) VALUES (10,'name10',{ts '1992-08-07 00:00:00.'},2)
GO
INSERT INTO lzy_test (id,name,birthday,school_code) VALUES (11,'name11',{ts '1965-08-08 00:00:00.'},2)
GO
INSERT INTO lzy_test (id,name,birthday,school_code) VALUES (12,'name12',{ts '1960-08-08 00:00:00.'},2)
GO
INSERT INTO lzy_test (id,name,birthday,school_code) VALUES (13,'name13',{ts '1967-04-08 00:00:00.'},2)
GO

 

解答问题:
select school_code,(
case((case(sign(convert(varchar(100),getdate()-DATEADD(year,datediff(year,h.personal_birthday,getdate()),h.personal_birthday),112)-19000101))
         when 0 then datediff(year,h.personal_birthday,getdate())+1
         when 1 then datediff(year,h.personal_birthday,getdate())+1
         when -1 then datediff(year,h.personal_birthday,getdate())
         end)-1)/5+1) 
when 1 then '30岁以下'
when 2 then '30岁以下'
when 3 then '30岁以下'
when 4 then '30岁以下'
when 5 then '30岁以下'
when 6 then '30岁以下'  
when 7 then '31-35'
when 8 then'36-45'
when 9 then'36-45'
when 10 then'46-55'
when 11 then'46-55'
else '56以上'
end) as 年龄段,  
count(*) as 人数  
from lzy_test 
group by (
case(((case(sign(convert(varchar(100),getdate()-DATEADD(year,datediff(year,h.personal_birthday,getdate()),h.personal_birthday),112)-19000101))
         when 0 then datediff(year,h.personal_birthday,getdate())+1
         when 1 then datediff(year,h.personal_birthday,getdate())+1
         when -1 then datediff(year,h.personal_birthday,getdate())
         end)-1)/5+1)  
when 1 then '30岁以下'
when 2 then '30岁以下'
when 3 then '30岁以下'
when 4 then '30岁以下'
when 5 then '30岁以下'
when 6 then '30岁以下'  
when 7 then '31-35'
when 8 then'36-45'
when 9 then'36-45'
when 10 then'46-55'
when 11 then'46-55'
else '56以上'  
end   )
,school_code

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值