按组划分的百分比 - oracle

时间:2015-02-06 13:51:18

标签: sql oracle group-by average

我有这个样本。

enter image description here

我需要的是获得每个键的平均值而不是键和值。但是,我使用的语法似乎给了我每个键和值的平均值。

select avg(value2),KEY,VALUE from testavg
GROUP BY key,value
order by key, value

否则会产生语法错误。我需要的结果如下:

10 A 0.96
10 B 0.04
12 C 1

但是我使用的陈述产生了上面不正确的结果。 这可以通过发出1个单独的oracle select语句来实现吗?我已经包含了创建整个表的语句。

CREATE TABLE "TESTAVG" 
       (    "KEY" NUMBER, 
        "VALUE" VARCHAR2(20 BYTE), 
        "VALUE2" NUMBER
       ) 

Insert into TESTAVG (KEY,VALUE,VALUE2) values (10,'A',12);
Insert into TESTAVG (KEY,VALUE,VALUE2) values (10,'A',13);
Insert into TESTAVG (KEY,VALUE,VALUE2) values (10,'B',1);
Insert into TESTAVG (KEY,VALUE,VALUE2) values (12,'C',20);

2 个答案:

答案 0 :(得分:4)

此查询可能会在较大的数据上运行得更快 - 只读取一次表:

  select distinct key, value,
         sum(value2) over (partition by key, value) / sum(value2) over (partition by key)  r
   from testavg
  /

         KEY VALUE                         R
  ---------- -------------------- ----------
          10 A                    .961538462
          10 B                    .038461538
          12 C                             1

答案 1 :(得分:0)

    select avg(value2),KEY from testavg
    GROUP BY key
    order by key;

8.66666666666666666666666666666666666667    10
20                                          12

编辑:规格仍然不明确,但这可能是你需要的......

with gr1 as (select key,sum(value2) sumvalue
            from testavg
            group by key)
,    gr2 as (select key,value,sum(value2) sumvalue
             from testavg
             GROUP BY key,value)
select gr1.key,gr2.value,gr2.sumvalue/gr1.sumvalue
from gr1
,    gr2
where gr1.key = gr2.key;


10  B   0.0384615384615384615384615384615384615385
12  C   1
10  A   0.9615384615384615384615384615384615384615