2014-09-22 73 views
1

我需要一些关于Oracle SQL中聚合问题的帮助。我希望这不是太简单,但我真的不知道该怎么做。Oracle SQL中的聚合

我有以下栏目:

Customer_ID (int) 
Countract_ID (int) 
  • 每个合同可以包括几个不同的客户
  • 每个客户可以包含在几个合同。

我需要添加一个新的列,其中包含每个成员(包括当前成员)的平均合同数量。例如:

ContractID |CustomerID | "AVG sum of contracs per member in the contract" 
123   | 11  |(3 + 2 + 1)/3 = 2 
123   | 22  |(3 + 2 + 1)/3 = 2 
123   | 33  |(3 + 2 + 1)/3 = 2 
321   | 11  |(3 + 2 + 2 + 1)/4 = 2 
321   | 55  |(3 + 2 + 2 + 1)/4 = 2 
321   | 22  |(3 + 2 + 2 + 1)/4 = 2 
321   | 88  |(3 + 2 + 2 + 1)/4 = 2 
987   | 11  |(3 + 2 + 1 + 1)/4 = 1.75 
987   | 55  |(3 + 2 + 1 + 1)/4 = 1.75 
987   | 99  |(3 + 2 + 1 + 1)/4 = 1.75 
987   | 77  |(3 + 2 + 1 + 1)/4 = 1.75 

有人知道什么是诸如聚合的查询吗?

+0

没有更多的时间 - 也许明天... – niyou 2014-09-22 14:54:39

+0

你的数据结构不适合我完全清楚。也许你可以使用[SqlFiddle](http://sqlfiddle.com/)来设置一个小模式? – funkwurm 2014-09-22 14:58:56

回答

0

下面是一种方法,我们使用了几个分析函数:count() over()avg() over()

-- sample of data 
with t1(Contractid ,Customerid) as(
    select 123 , 11 from dual union all 
    select 123 , 22 from dual union all 
    select 123 , 33 from dual union all 
    select 321 , 11 from dual union all 
    select 321 , 55 from dual union all 
    select 321 , 22 from dual union all 
    select 321 , 88 from dual union all 
    select 987 , 11 from dual union all 
    select 987 , 55 from dual union all 
    select 987 , 99 from dual union all 
    select 987 , 77 from dual 
) 
-- the query 
-- analytic functions cannot be nested, thus inline vew 
select contractid 
     , customerid 
     , avg(cnt) over(partition by contractid) as average 
    from (select contractid 
       , customerid  
       , count(contractid) over(partition by customerid) cnt 
      from t1) 
order by contractid, customerid 

结果:

CONTRACTID CUSTOMERID AVERAGE 
---------- ---------- ---------- 
     123   11   2 
     123   22   2 
     123   33   2 
     321   11   2 
     321   22   2 
     321   55   2 
     321   88   2 
     987   11  1.75 
     987   55  1.75 
     987   77  1.75 
     987   99  1.75 

11 rows selected 

Sqlfiddle demo

+0

非常感谢!我很好奇,这个查询是只能用分析函数实现的,还是可以用简单的方式实现? – Omri 2014-09-22 18:14:01

+0

@ user3928712当你说“简单的方式”时,你的意思是什么?不,我相信有不止一些方法可以完成,并且效率不同。 – 2014-09-22 18:27:59

+0

我想问这个计算是否可以在没有解析函数的查询中实现。而已。 – Omri 2014-09-23 06:24:50