SQL语句 按年龄段分组统计人数问题

2024-11-15 15:43:51
推荐回答(5个)
回答(1):

先确保你的出生年月是datetime的日期类型,语法如下。
select
case
when
datediff(year,出生年月,getdate())
<=
20
then
'20岁年龄段'
when
datediff(year,出生年月,getdate())
between
21
and
25
then
'21-25年龄段'
else
'25以上年龄段'
end
as
年龄段,count(1)
as
年龄段人数
from

group
by
case
when
datediff(year,出生年月,getdate())
<=
20
then
'20岁年龄段'
when
datediff(year,出生年月,getdate())
between
21
and
25
then
'21-25年龄段'
else
'25以上年龄段'
end
也可以试试
select
sum(case
when
datediff(year,出生年月,getdate())
<=
20
then
1
else
0
end)
'20岁年龄段',
sum(case
when
datediff(year,出生年月,getdate())
between
21
and
25
then
1
else
0
end)
'21-25年龄段',
sum(case
when
datediff(year,出生年月,getdate())
>
25
then
1
else
0
end)
'25以上年龄段'
from

回答(2):

--很简单啊,楼主请看:
--以下在SQL2005测试通过。
create
table
#t(Uname
varchar(10),age
int)
insert
#t
select
'啊啊',19
union
all
select
'信息',23
union
all
select
'宝宝',31
union
all
select
'喔喔',21
union
all
select
'米米',6
select
nnd
as
'年龄段',count(*)
as
'人数'
from
(
select
case
when
age>=1
and
age<=10
then
'1-10'
when
age>=11
and
age<=20
then
'11-20'
when
age>=21
and
age<=30
then
'21-30'
when
age>=31
and
age<=40
then
'31-40'
end
as
nnd,uname
from
#t
)
a
group
by
nnd

回答(3):

用程序更好实现,sql语句可以实现,但很麻烦。

回答(4):

--很简单啊,楼主请看:
--以下在SQL2005测试通过。
create
table
#t(Uname
varchar(10),age
int)
insert
#t
select
'啊啊',19
union
all
select
'信息',23
union
all
select
'宝宝',31
union
all
select
'喔喔',21
union
all
select
'米米',6
select
nnd
as
'年龄段',count(*)
as
'人数'
from
(
select
case
when
age>=1
and
age<=10
then
'1-10'
when
age>=11
and
age<=20
then
'11-20'
when
age>=21
and
age<=30
then
'21-30'
when
age>=31
and
age<=40
then
'31-40'
end
as
nnd,uname
from
#t
)
a
group
by
nnd

回答(5):

select count(*) from table limit1,10
我只是将它按照10的差距取出数据
可是怎么不为0,没做过诶