从SQL Server的雇员表返回按年龄间隔划分的百分比

7eumitmz  于 2023-01-08  发布在  SQL Server
关注(0)|答案(4)|浏览(132)

我有一个表employees[employee_id,age],我希望返回年龄在18到20岁之间以及26到40岁之间的雇员的百分比,如下所示:

Age Interval Percent
18-20          35%
26-40          40 %

谢啦,谢啦

Select t.range as [age interval] , Count(*) as 'number of appereances' from
(Select case when age between 18 and 26 then '18-26'
when age between 26-40 then '26-40' end as range from employees) t
group by t.range
dsekswqp

dsekswqp1#

select '18-20',
    count(case when age between 18 and 20 then 1 end) * 100.0 / count(*)
from employees

union all 

select '26-40',
    count(case when age between 26 and 40 then 1 end) * 100.0 / count(*)
from employees

SQL小提琴示例#1
你也可以写一个稍微干净一点(更容易维护)的版本,如下所示:

select cast(r.Start as varchar(3)) + '-' + cast(r.[End] as varchar(3)),
    count(case when e.age between r.Start and r.[End] then 1 end) * 100.0 / (select count(*) from employees) 
from (
    select 18 as Start, 20 as [End]
    union all      
    select 21 as Start, 25 as [End]
    union all      
    select 26 as Start, 40 as [End]
) r  
left outer join employees e on e.age between r.Start and r.[End]
group by cast(r.Start as varchar(3)) + '-' + cast(r.[End] as varchar(3))

SQL小提琴示例#2

k4ymrczo

k4ymrczo2#

你通常想用windows函数做这样的事情:

Select t.range as [age interval] , Count(*) as 'number of appereances',
       cast(count(*)*100.0/tot as varchar(256))+'%' as 'percent'
from (Select (case when age between 18 and 26 then '18-26'
                  when age between 26 and 40 then '26-40'
              end) as range,
             count(*) over (partition by NULL) as tot
      from employees) t
group by t.range

我还按照示例中的格式对数字进行了格式化。

mrphzbgm

mrphzbgm3#

选择

SUM(CASE WHEN [dbo].[GetAge](DateOfBirth) < 20 THEN 1 ELSE 0 END) AS [Under_20],
    SUM(CASE WHEN [dbo].[GetAge](DateOfBirth) BETWEEN 20 AND 25 THEN 1 ELSE 0 END) AS [Age_21_25],
    SUM(CASE WHEN [dbo].[GetAge](DateOfBirth) >=26 THEN 1 ELSE 0 END) AS [Age_26_Elder]

from AspNetUsers(nolock) au inner join AspNetUserRoles(nolock) aur
on au.Id=aur.UserId inner join AspNetRoles(nolock) ar on aur.RoleId=ar.Id
Inner join StudentProfiles(nolock) st on au.Id = st.UserId
0yycz8jy

0yycz8jy4#

Select 
CAST(ROUND(count(case when 18 <= age and  age < 26 then 1 end) * 100.0 / count(*),2)AS NUMERIC(8,2)) as '18-26'
,CAST(ROUND(count(case when 26 <= age and  age < 40 then 1 end) * 100.0 / count(*),2)AS NUMERIC(8,2)) as '26-40'
From employees

加obtimesée

相关问题