2

我正在尝试获取一组特定值所具有的行的百分比。最好用例子来解释。我可以非常简单地使用 ratio-to-report 函数和 over() 对每一列执行此操作,但我遇到了多个分组的问题

假设表有 2 列:

column a         column b
1000             some data
1100             some data
2000             some data
1400             some data
1500             some data

通过以下查询,我可以得到这个域集,每个是总行数的 20%

select columna, count(*), trunc(ratio_to_report(count(columna)) over() * 100, 2) as perc
from table
group by columna
order by perc desc;

但是,我需要的是例如确定包含 1000、1400 或 2000 的行的百分比和计数;通过查看它,您可以知道它的 60%,但需要查询才能返回。这需要高效,因为查询将针对数百万行运行。就像我之前说的,我对单个值及其百分比进行了处理,但是让我感到困惑的是倍数。

似乎我需要能够在某处放置一个 IN 子句,但这些值不会每次都是这些特定值。如果有意义的话,我需要从另一个表中获取它的“IN”部分的值。我想我需要某种多重分组。

4

2 回答 2

1

您可能正在寻找类似的东西

SQL> ed
Wrote file afiedt.buf

  1  with x as (
  2    select 1000 a from dual
  3    union all
  4    select 1100 from dual
  5    union all
  6    select 1400 from dual
  7    union all
  8    select 1500 from dual
  9    union all
 10    select 2000 from dual
 11  )
 12  select (case when a in (1000,1400,1500)
 13               then 1
 14               else 0
 15           end) bucket,
 16         count(*),
 17         ratio_to_report(count(*)) over ()
 18    from x
 19   group by (case when a in (1000,1400,1500)
 20               then 1
 21               else 0
 22*          end)
SQL> /

    BUCKET   COUNT(*) RATIO_TO_REPORT(COUNT(*))OVER()
---------- ---------- -------------------------------
         1          3                              .6
         0          2                              .4
于 2011-03-11T18:53:32.770 回答
0

我不确定我是否完全理解这个要求,但你需要ratio_to_report吗?看看下面的内容,让我知道这与你想要的有多接近,我们可以从那里开始工作!

T1 是包含您的样本数据的表

create table t1(a primary key) as
   select 1000 as a from dual union all
   select 1100 as a from dual union all
   select 1400 as a from dual union all
   select 1500 as a from dual union all
   select 2000 as a from dual;

T2 是您提到的查找表(您在其中获取 ID 列表)

create table t2(a primary key) as
   select 1000 as a from dual union all
   select 1400 as a from dual union all
   select 2000 as a from dual;

从 T1->T2 的左连接将返回 T1 中的所有行与 T2 中的所有匹配行配对。对于您的集合 (T2) 中不存在的 T1 中的每个 A,结果将用 NULL 填充。COUNT()我们可以利用不计算(呵呵)空值的事实。

select count(t1.a) as num_rows
      ,count(t2.a) as in_set
      ,count(t2.a) / count(t1.a) as shr_in_set
  from t1
  left 
  join t2 on(t1.a = t2.a);

运行查询的结果是:

  NUM_ROWS     IN_SET SHR_IN_SET
---------- ---------- ----------
         5          3         ,6
于 2011-03-11T22:19:08.990 回答