如何从出生年月中统计出年龄,并计算出占总数的百分比?

powbcom 2006-03-27 10:03:21

CREATE TABLE #Test(id int, birth datetime)

INSERT INTO #Test select 1, '1978-10-12'
union all select 2, '1981-5-21'
union all select 3, '1975-12-3'
union all select 4, '1980-10-12'

如何从出生年月中统计出年龄,并计算出占总数的百分比?


年龄 百分比 数量
26 25% 1
27 25% 1

...全文
332 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
aniude 2006-03-27
  • 打赏
  • 举报
回复
刚刚去吃饭了,没看,居然结贴了
aniude 2006-03-27
  • 打赏
  • 举报
回复
CREATE TABLE #Test(id int, birth datetime)

INSERT INTO #Test select 1, '1978-10-12'
union all select 2, '1981-5-21'
union all select 3, '1975-12-3'
union all select 4, '1980-10-12'


select 年龄=datediff(day,birth,getdate()),
百分比=cast(count(2)*100/(select count(1) from #Test) as varchar(10))+'%',
数量=count(1)
from #Test group by datediff(day,birth,getdate())
tian790317 2006-03-27
  • 打赏
  • 举报
回复
select '年龄'=datediff(yy,birth,getdate()),count(datediff(yy,birth,getdate())), count(*)*1.0/(select count(*) from #test ) from #test group by datediff(yy,birth,getdate())
撸大湿 2006-03-27
  • 打赏
  • 举报
回复
CREATE TABLE #Test(id int, birth datetime)

INSERT INTO #Test select 1, '1978-10-12'
union all select 2, '1981-5-21'
union all select 3, '1975-12-3'
union all select 4, '1980-10-12'


--年龄 百分比 数量
--26 25% 1
--27 25% 1


select count(1) from #test
select datediff( yy,birth,getdate()) 年龄
,convert(nvarchar(100),convert (float,count(year(birth)))/(select count(1) from #test )*100)+'%'比例
,count(year(birth)) 数量
from #test group by datediff( yy,birth,getdate())
drop table #test
huailairen 2006-03-27
  • 打赏
  • 举报
回复
select datediff(yy,birth,getdate()) as 年龄,cast(ceiling(count(*)*1.0/(select count(*) from #test )*100) as varchar(3))+'%' as 百分比,count(*) as 数量
from #test
group by birth
order by datediff(yy,birth,getdate())

结果
年龄 百分比 数量
----------- ---- -----------
25 25% 1
26 25% 1
28 25% 1
31 25% 1

(所影响的行数为 4 行)
huailairen 2006-03-27
  • 打赏
  • 举报
回复
select datediff(yy,birth,getdate()),cast(ceiling(count(*)*1.0/(select count(*) from #test )*100) as varchar(3))+'%',count(*)
from #test
group by birth
order by datediff(yy,birth,getdate())
子陌红尘 2006-03-27
  • 打赏
  • 举报
回复
CREATE TABLE #Test(id int, birth datetime)

INSERT INTO #Test select 1, '1978-10-12'
union all select 2, '1981-5-21'
union all select 3, '1975-12-3'
union all select 4, '1980-10-12'


select
datediff(yy,birth,getdate()) as age,
rtrim(count(*)*100/(select count(1) from #Test))+'%' as [percent],
count(*) as num
from #Test
group by datediff(yy,birth,getdate())


drop table #Test

34,594

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧