1

我怎么了group bySQL小提琴

with age_range as (
    select 0 as "bottom", 29 as "top", '<30' as "range" from dual union
    select 30, 34, '30-34' from dual union
    select 35, 39, '35-59' from dual union
    select 40, 49, '40-49' from dual union
    select 50, 54, '50-54' from dual
)
select 
    ar."range" as Age,
    count(case when Department = 'IT' and Gender = 'M' then 1 end) as IT_Male,
    count(case when Department = 'IT' and Gender = 'F' then 1 end) as IT_Female,
    count(case when Department = 'Finance' and Gender = 'M' then 1 end) as Finance_Male,
    count(case when Department = 'Finance' and Gender = 'F' then 1 end) as Finance_Female,
    count(case when Department = 'HR' and Gender = 'M' then 1 end) as HR_Male,
    count(case when Department = 'HR' and Gender = 'F' then 1 end) as HR_Female
from 
    JOB_Details jd
    inner join
    age_range ar on jd.Age between ar."bottom" and ar."top"
group by ar."range"
order by ar."bottom"
4

2 回答 2

2

如果您愿意,ORDER BY ar.bottom则需要将其包含在GROUP BY

with age_range as 
(
    select 0 as bottom, 29 as top, '<30' as range from dual union
    select 30, 34, '30-34' from dual union
    select 35, 39, '35-59' from dual union
    select 40, 49, '40-49' from dual union
    select 50, 54, '50-54' from dual
)
select 
    ar.range as Age,
    count(case when Department = 'IT' and Gender = 'M' then 1 end) as IT_Male,
    count(case when Department = 'IT' and Gender = 'F' then 1 end) as IT_Female,
    count(case when Department = 'Finance' and Gender = 'M' then 1 end) as Finance_Male,
    count(case when Department = 'Finance' and Gender = 'F' then 1 end) as Finance_Female,
    count(case when Department = 'HR' and Gender = 'M' then 1 end) as HR_Male,
    count(case when Department = 'HR' and Gender = 'F' then 1 end) as HR_Female
from JOB_Details jd
inner join age_range ar 
  on jd.Age between ar.bottom and ar.top
group by ar.range, ar.bottom
order by ar.bottom

请参阅带有演示的 SQL Fiddle

于 2012-10-12T10:59:55.580 回答
1

Remove your last:

order by ar."bottom"
于 2012-10-12T10:57:29.423 回答