sql - Alternative to case statement -
i need suggestions on writing sql query other using case
statement in oracle.i have table named system_specs
following data
customer_id disk_space_allocated c001 44g c002 1300g c003 1503g c004 1780g
i wrote following sql query using oracle case statement count of customer_id
based on ranges disk_space_allocated
select case when to_number(substr(disk_space_allocated,0,length(disk_space_allocated) -1 )) <= 300 '1-300' when to_number(substr(disk_space_allocated,0,length(disk_space_allocated) -1 )) <= 500 '300-500' when to_number(substr(disk_space_allocated,0,length(disk_space_allocated) -1 )) <= 700 '500-700' when to_number(substr(disk_space_allocated,0,length(disk_space_allocated) -1 )) <= 900 '700-900' else '900+' end diskallocated, count(*) number_of_customers system_specs group case when to_number(substr(disk_space_allocated,0,length(disk_space_allocated) -1 )) <= 300 '1-300' when to_number(substr(disk_space_allocated,0,length(disk_space_allocated) -1 )) <= 500 '300-500' when to_number(substr(disk_space_allocated,0,length(disk_space_allocated) -1 )) <= 700 '500-700' when to_number(substr(disk_space_allocated,0,length(disk_space_allocated) -1 )) <= 900 '700-900' else '900+' end;
can query written other form?
firstly logic wrong calculating <=700 , saying between 500-700, if <=700 default <=500 , <=300. can not call between 500-700. try below query
select count(*) number_of_customers,b.var "less below value" system_specs a, (select 300 + (level-1)*200 var dual connect level <= 4) b to_number(substr(a.disk_space_allocated,0,length(a.disk_space_allocated) -1 )) <= b.var group b.var order b.var
final answer question of @alex
with ranges ( select case when level = 1 0 else 100 end + (level-1) * 200 low_value, case when level = 5 99999999 else 100 + (level) * 200 end high_value dual connect level <= 5 ) select r.low_value ||'-'|| r.high_value diskallocated, count(*) number_of_customers ranges r left join system_specs ss on to_number(substr(ss.disk_space_allocated, 1, length(ss.disk_space_allocated) -1 )) > r.low_value , to_number(substr(ss.disk_space_allocated, 1, length(ss.disk_space_allocated) -1 )) <= r.high_value group r.low_value, r.high_value order r.low_value, r.high_value;
Comments
Post a Comment