【问题标题】:Aggregation in Oracle SQLOracle SQL 中的聚合
【发布时间】:2014-11-16 14:02:42
【问题描述】:

我需要一些有关 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

有人知道聚合之类的查询是什么吗?

【问题讨论】:

  • 没时间了——也许明天……
  • 你的数据结构对我来说并不完全清楚。或许你可以使用SqlFiddle 来建立一个小的Schema?

标签: sql oracle aggregation


【解决方案1】:

这是一种方法,我们使用了几个分析函数: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

【讨论】:

  • 非常感谢!我很好奇,这个查询是只能用解析函数实现,还是也可以用简单的方式实现?
  • @user3928712 当你说“简单的方法”时,你到底是什么意思?不,我确信有很多方法可以完成它,但效率不同。
  • 我想问这个计算是否可以在没有解析函数的查询中实现。就是这样。
猜你喜欢
  • 2018-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-10
  • 2013-11-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多