2014-09-22 51 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