1

我有一张表 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
4

3 回答 3

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 小提琴示例 #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

于 2012-07-17T15:14:44.993 回答
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 

我还按照您的示例中的数字格式化了数字。

于 2012-07-17T15:31:44.053 回答
-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

于 2013-05-23T11:22:01.167 回答