sql 年齡段統計

2021-08-29 22:04:01 字數 2056 閱讀 1496

表employee(empid,birthday)  

部分資料:  

empid       birthday  

1                 1964-3-2  

2                 1980-5-9  

3                 1972-9-30  

....      

想得到按年齡段的人數,比如說20-30歲的員工數,30-40歲的員工數,40-50歲的員工數,50歲以上的員工數  

即由員工表得到以下的統計資料  

agelevel     count  

20-30           30  

30-40           5  

40-50           8  

50歲以上     7  

怎樣寫這條語句?

語句如下::

select   n'agelevel'=(case((datediff(year,birthday,getdate())-1)/10)   when   2   then   '21-30'   when   3   then   '31-40'   when   4   then'41-50'   else   '50以上'   end),  

count(*)   as   count    

from    

employee  

group   by   (case((datediff(year,birthday,getdate())-1)/10)   when   2   then   '21-30'   when   3   then   '31-40'   when   4   then'41-50'   else   '50以上'   end   )

或者以10歲為遞增

select

cast(f1*10+1 as varchar(3))+'-'+cast(f1*10+10 as varchar(3)) as 年齡段,f2 as 人數

from

(select datediff(d,a0111,getdate())/365/10 as f1,

count(*) as f2

from dbo.a001 

group by datediff(d,a0111,getdate())/365/10) a

order by cast(f1*10+1 as varchar(3))+'-'+cast(f1*10+10 as varchar(3))

第二種形式

16-20 21-30 31-40 41-50 51-60 61-70

0        8         9         8         5         3

select

sum(

case when datediff(year, a0111, getdate()) between 16 and 20 then 1 else 0 end) as '16-20',

sum(case when datediff(year, a0111, getdate()) between 21 and 30 then 1 else 0 end) as '21-30',

sum(case when datediff(year, a0111, getdate()) between 31 and 40 then 1 else 0 end) as '31-40',

sum(case when datediff(year, a0111, getdate()) between 41 and 50 then 1 else 0 end) as '41-50',

sum(case when datediff(year, a0111, getdate()) between 51 and 60 then 1 else 0 end) as '51-60',

sum(case when datediff(year, a0111, getdate()) between 61 and 70 then 1 else 0 end) as '61-70'

from

dbo.a001

147 統計各年齡段人數

函式fun的功能是 統計各年齡段的人數,n個年齡通過呼叫隨機函式獲取,並放在主函式的age陣列中,要求函式0 9歲的人數放在d 0 以此類推,把100歲 含100歲 以上的年齡人數都放在d 10 中,結構在主函式中輸出。define crt secure no warnings include de...

MySQL按年齡段查詢

下面是專案中按照男女年齡段統計的核心sql sql view plain copy print count tr.id as 體檢總人數 sum case when s.1 then 1 else 0 end as 男體檢總數 sum case when s.0 then 1 else 0 end ...

MySQL按年齡段查詢

下面是專案中按照男女年齡段統計的核心sql count tr.id as 體檢總人數 sum case when s.1 then 1 else 0 end as 男體檢總數 sum case when s.0 then 1 else 0 end as 女體檢總數 sum case when s.1...