Question

I am selecting records within different ranges with a select statement like

select t.range as profit_range, count(*) as number_ of_occurences   from (
  select case 
    when t.range between  100000000 and  200000000 then '100 million - 200 million'
    when t.range between  200000000 and  300000000 then '200 million - 300 million'
    .
    .
    .
    when t.range between  1000000000 and  2000000000 then '1000 million - 2000 million'
    else 'Greater then 2000 milions' end as range
  from tbl_profit) t
group by profit_range

This works but the order of the resulting rows is not correct

 Profit_Range                       No_of_occurences    
 100 million  - 200 million           4
 1000 million - 2000 million          1
 200 million  - 300 million           4

How do I order the results to appear in the right order?

Was it helpful?

Solution

select t.range as [profit range], count(*) as [number of occurences]
from (
  select case 
    when profit between  100000000 and  200000000 then '100 million - 200 million'
    when profit between  200000000 and  300000000 then '200 million - 300 million'
    .
    .
    .
    when profit between  1000000000 and  2000000000 then '1000 million - 2000 million'
    else 'Greater then 2000 milions' end as range
    from tbl_profit) t
group by t.range
Order by SUBSTR(t.range,1,LOCATE(‘million’,t.range)-1)

You can extract starting number from range using SUBSTR() and LOCATE functions and order result according to extracted number

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top