Group by on the basis of conditions
I have a table:
spent totalsent totalused
----------------------------开发者_Python百科
4 1234 123
6 12 4
7 45 32
I need to group totalused/totalsent in groups of 0 <= spent <= 5, 6 <= spent <= 10 and so on.
How can this be done?
If you are just wanting groups of 5, you can probably just set up a column to group on which divides by 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)
)
This code doesn't quite handle 0 or anything below 0 correctly since it puts everything in the lower group and labels it 1-5
, but your requirements are a little vague in that respect.
Also, this is a sparse grouping so there will only be a row for 11-15 if there is source data which allows it to be produced.
精彩评论