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

プラスオブティミゼ

于 2013-05-23T11:22:01.167 に答える