MySQL版本。不會在SQL Server中工作,也不會在Oracle中工作。 SQL Fiddle
select *, IT_Male + IT_Female + Finance_Male + Finance_Female + HR_Male + HR_Female as Total
from (
select
ar.`range` as Age,
count(Department = 'IT' and Gender = 'M' or null) as IT_Male,
count(Department = 'IT' and Gender = 'F' or null) as IT_Female,
count(Department = 'Finance' and Gender = 'M' or null) as Finance_Male,
count(Department = 'Finance' and Gender = 'F' or null) as Finance_Female,
count(Department = 'HR' and Gender = 'M' or null) as HR_Male,
count(Department = 'HR' and Gender = 'F' or null) 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
) s
union
select
'Total',
count(Department = 'IT' and Gender = 'M' or null),
count(Department = 'IT' and Gender = 'F' or null),
count(Department = 'Finance' and Gender = 'M' or null),
count(Department = 'Finance' and Gender = 'F' or null),
count(Department = 'HR' and Gender = 'M' or null),
count(Department = 'HR' and Gender = 'F' or null),
count(*)
from JOB_Details
Oracle版本而無需外部表或視圖:SQL Fiddle
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 s.*, IT_Male + IT_Female + Finance_Male + Finance_Female + HR_Male + HR_Female as Total
from (
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"
) s
union
select
'Total',
count(case when Department = 'IT' and Gender = 'M' then 1 end),
count(case when Department = 'IT' and Gender = 'F' then 1 end),
count(case when Department = 'Finance' and Gender = 'M' then 1 end),
count(case when Department = 'Finance' and Gender = 'F' then 1 end),
count(case when Department = 'HR' and Gender = 'M' then 1 end),
count(case when Department = 'HR' and Gender = 'F' then 1 end),
count(*)
from JOB_Details
您好,您的建議是good.as我的反饋,但它並沒有在Oracle SQL.Anyway工作,非常感謝你。 – goh6319
@ goh6319然後它是Oracle,而不是標籤中的MySQL,而不是SQL Server? –
@ goh6319增加甲骨文 –