按条件分组

时间:2010-12-12 05:20:20

标签: sql oracle oracle10g group-by

我有一张桌子:

spent  totalsent  totalused
----------------------------
4      1234       123
6      12         4
7      45         32

我需要在0 <=花费&lt; = 5,6&lt; =花费&lt; = 10等等的组中对totalused / totalsent进行分组。

如何做到这一点?

1 个答案:

答案 0 :(得分:2)

如果您只是想要5个组,您可以设置一个分组列,其中除以5。

with my_source_data as (
  select 4 as spent, 1234 as totalsent, 123 as totalused from dual union all
  select 6 as spent, 12 as totalsent, 4 as totalused from dual union all
  select 7 as spent, 45 as totalsent, 32 as totalused from dual
)
select 
  (spent_group -1) * 5 + 1 as lower_bound, 
  spent_group * 5  as upper_bound, totalsent, totalused 
from (
  select 
    greatest(ceil(spent/5),1) as spent_group, 
    sum(totalsent) as totalsent, sum(totalused) totalused
  from my_source_data  
  group by greatest(ceil(spent/5),1)
)

此代码不能正确处理0或0以下的任何内容,因为它将所有内容放在较低的组中并将其标记为1-5,但在这方面您的要求有点模糊。

此外,这是一个稀疏分组,因此如果有源数据允许生成,则只有11-15行。