SQL Oracle-查找案例范围内的计数比率



我基本上是在计算每个年龄段的事故中有过错的人的比例。但我陷入了困境,无法从创建不同范围的子查询中计算出实际的比率。这是我想写的片段——即使它毫无意义。有人能帮我做这个吗?干杯

无意义的东西是from SUBQ,因为我们得到了错误table or view does not existwhere age_groups = age_groups。我基本上是在尝试创建一个条件,以匹配我在外部select子句中分组的范围。

select
age_groups,
100*trunc(COUNT(*) / (select COUNT(*) from SUBQ where age_groups = age_groups),3) ratio
from
(
select CASE_ID, AT_FAULT, case
when PARTY_AGE <= 18 then 'underage'
when PARTY_AGE > 18 and PARTY_AGE <= 21 then 'young I'
when PARTY_AGE > 21 and PARTY_AGE <= 24 then 'young II'
when PARTY_AGE > 24 and PARTY_AGE <= 60 then 'adult'
when PARTY_AGE > 60 and PARTY_AGE <= 64 then 'elder I'
else 'elder II'
end as age_groups
from PARTY
) SUBQ
where AT_FAULT = 1
group by age_groups
order by 2 desc;

注:。真正的问题是这样表述的:对于每个年龄段的司机,找出司机是过错方的案件比例。将此比率显示为百分比,并按每个年龄组显示。

select age_groups,
100*trunc(Sum(At_Fault)/count(*),3) ratio
from
(
select CASE_ID, AT_FAULT, case
when PARTY_AGE <= 18 then 'underage'
when PARTY_AGE > 18 and PARTY_AGE <= 21 then 'young I'
when PARTY_AGE > 21 and PARTY_AGE <= 24 then 'young II'
when PARTY_AGE > 24 and PARTY_AGE <= 60 then 'adult'
when PARTY_AGE > 60 and PARTY_AGE <= 64 then 'elder I'
else 'elder II'
end as age_groups
from PARTY
) SUBQ
group by age_groups
order by 2 desc;

您必须省略"其中AT_FAULT=1",因为您要计算AT_FAULT=0的记录。

最新更新