计算类似记录中的记录百分比

时间:2018-06-15 08:39:49

标签: oracle plsql

我有桌子:

ID    Type
----  ----
1     a
1     b
2     a
2     a
3     b

表格中包含第一张表中的ID名称 - n:

ID    Name
----  ----
1     name1
2     name2
3     name3

我需要在PL / SQL中查询相同id(按ID分组)的所有类型的类型出现的计数百分比。

结果必须是:

Name   a%   b%     row
---    ----  ---   ---
name1  50    50   1
name2  100   0    2
name3  0     100  3

我试过了:

select 
    n.name,
    a.perc as "a%",
    b.perc as "b%",
    row_number() over (
        order by name asc
    ) mf_rownumber
from n n
left join
    (select 
        id,
        round(100 * (count(*) / sum(count(*)) over ()), 2) perc
    from t
    where (type = 'a')
    group by id) a
    on a.id = n.id
left join
    (select 
        id,
        round(100 * (count(*) / sum(count(*)) over ()), 2) perc
    from t
    where (type = 'b')
    group by id) b
    on b.id = n.id;

我得到的是所有行中每种类型的百分比:

Name    a%   b%     row
---     ----  ---   ---
name1   20    20   1
name2   40    0    2
name3   0     20   3

但是我需要计算相同ID的边界内的所有内容,而不是所有行。

2 个答案:

答案 0 :(得分:2)

我认为它可以简化很多: http://sqlfiddle.com/#!4/6bb2a/20

 select 
    n.name,
    round(100 * (sum(case when type='a' then 1 else 0 end) / count(*)), 2) as "a%",
    round(100 * (sum(case when type='b' then 1 else 0 end) / count(*)), 2) as "b%",
    row_number() over (order by name asc ) mf_rownumber
from n 
left join t on t.id = n.id
group by n.name

答案 1 :(得分:1)

我会做这样的事情:

select 
    n.name,
    n.id, 
    count(case when type='a' then 1 end)/count(*)*100 as "a%",
    count(case when type='b' then 1 end)/count(*)*100 as "b%" 
from n left join t on a.id=n.id 
group by n.id;