在sql中查找变量在另一个变量级别上的比例

时间:2018-05-17 06:45:05

标签: sql group-by

我有以下数据:

group_class y_prop
grp_1       1
grp_1       0
grp_2       1
grp_1       0
grp_1       0
grp_1       1
grp_3       0
grp_3       0
grp_3       0
grp_1       0
grp_1       0
grp_1       1
grp_1       0
grp_1       0
grp_3       1
grp_2       0
grp_1       0
grp_2       0
grp_1       0
grp_1       0
grp_2       0
grp_1       0
grp_1       1
grp_1       0
grp_1       0
grp_2       1
grp_2       0
grp_2       0

我想在每个group_Class中找到y_prop的比例,如下所示:

group_class y_prop
grp_3       0.25
grp_2       0.29
grp_1       0.29

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

http://sqlfiddle.com/#!4/28c4c/7/0

CREATE TABLE Table1
    (group_class varchar2(5), y_prop int)
;

INSERT ALL 
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_1', 1)
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_1', 0)
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_2', 1)
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_1', 0)
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_1', 0)
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_1', 1)
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_3', 0)
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_3', 0)
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_3', 0)
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_1', 0)
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_1', 0)
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_1', 1)
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_1', 0)
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_1', 0)
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_3', 1)
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_2', 0)
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_1', 0)
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_2', 0)
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_1', 0)
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_1', 0)
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_2', 0)
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_1', 0)
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_1', 1)
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_1', 0)
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_1', 0)
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_2', 1)
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_2', 0)
    INTO Table1 (group_class, y_prop)
         VALUES ('grp_2', 0)
SELECT * FROM dual
;

查询 -

select group_class, round(y_prop,2) as y_prop from (
select group_class, avg(y_prop) as y_prop
from Table1
group by group_class
order by group_class desc);

输出 -

GROUP_CLASS Y_PROP
grp_3       0.25
grp_2       0.29
grp_1       0.24