我有一些查询MySQL数据库的经验,我试图学习如何在Oracle中做同样的事情。理论上有多难。让我们说我有一个DEMOGRAPHICS表,其中包含以下列:DATE_OF_BIRTH,GENDER,RACE,ETHNICITY。还有一个CAR表,其中列有MAKE,列出了不同品牌的汽车(丰田,福特等)。我如何创建一个统计报告,列出每个汽车品牌和相应的百分比率列MALE,FEMALE,WHITE,ASIAN,BLACK,HISPANIC,NOT HISPANIC和两个年龄段列(18-30和50-70)。百分比应四舍五入到小数点后两位。它应该如下所示: enter image description here 我将不胜感激任何帮助,包括对类似查询的引用。 谢谢!
答案 0 :(得分:0)
需要更多信息。 WHITE,ASIAN,BLACK< ==这些都属于RACE专栏 HISPANIC,而不是HISPANIC< ==这些属于ETHNICITY专栏
答案 1 :(得分:0)
drop table demographics
drop table car
create table car(MAKE_ID number primary key, MAKE varchar2(30));
create table demographics(DATE_OF_BIRTH date , GENDER varchar2(10), RACE varchar2(30), ETHNICITY varchar2(30), MAKE_ID references car);
--insert into car table
insert into car values(1,'Toyota');
insert into car values(2,'Ford');
insert into car values(3,'GM');
--inserts 1000 rows into the demographics table
insert into demographics
select trunc(sysdate) - level as dob
,case when mod(level,2)=0 then 'MALE' else 'FEMALE' end as gender
,case when mod(level,2)=0 then 'WHITE' else 'BLACK' end as race
,case when mod(level,4)=0 then 'ASIAN'
when mod(level,3)=0 then 'HISPANIC'
when mod(level,2)=0 then 'NOT HISPANIC'
else 'LATINO'
end as ethnicity
,case when mod(level,3)=0 then 3
when mod(level,2)=0 then 2
when mod(level,1)=0 then 1
end as make_id
from dual
connect by level<=1000;
select make
,round((cnt_MAKE/tot_cnt)*100,2) as MALE_PERCENT
,round((cnt_MAKE/tot_cnt)*100,2) as FEMALE_PERCENT
from(
select a.make
,count(case when b.gender ='MALE' then 1 end) as cnt_MALE
,count(case when b.gender ='FEMALE' then 1 end) as cnt_FEMALE
,count(case when b.race ='WHITE' then 1 end) as cnt_WHITE
,count(case when b.ethnicity ='ASIAN' then 1 end) as cnt_ASIAN
,count(case when b.race ='BLACK' then 1 end) as cnt_BLACK
,count(case when b.ethnicity ='HISPANIC' then 1 end) as cnt_HISPANIC
,count(case when b.ethnicity ='NOT HISPANIC' then 1 end) as cnt_NOT_HISPANIC
,count(*) as tot_cnt
from car a
join demographics b
on a.make_id=b.make_id
group by a.make
)