根据员工表SQL Server的年龄间隔返回百分比

时间:2012-07-17 15:06:53

标签: sql-server percentage

我有一个员工[employee_id,年龄],我希望返回年龄在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

3 个答案:

答案 0 :(得分:3)

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 Fiddle Example #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 Fiddle Example #2

答案 1 :(得分:1)

您通常希望使用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 

我还在你的例子中格式化了你的数字。

答案 2 :(得分:-1)

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

加上obtimisée