Grouping SQL Results Based on certain ranges in an int field.MS SQL 2008

I have a query which returns the results i need, will be putting this into a view as i'll need this for a few different things, one of the things i need it for is to group based on a particular field.

the field is called length, it is in kilometres, i want to group records based on the length as follows:

0-5 = group1
5-10 = group 2
10-20 = group 3
20-40 = group 4
>40 = group 5

could i use a case statement within the view to generate a column with the group name based on the ranges above, and then do a query on this view. grouping by that group column to collate the results?

to keep it simple please assume the following table:
id, roadname, city, state, roadlength

where roadlength is the column i want to group on.


HRT_HSVAsked:
Who is Participating?
 
sventhanConnect With a Mentor Commented:
select roadname, city, state,
case
  when length between 0 and 5 then 'group1'
  when length between 6 and 10 then 'group2'
  when length between 11 and 20 then 'group3'
  when length between 21 and 40 then 'group4'
  when length>41 then 'group5' end
end as mygroup
from yourtable
0
 
sshah254Connect With a Mentor Commented:
Yes, you can use a case statement.

case
  when length between 0 and 5 then 'group1'
  when length between 6 and 10 then 'group2'
  ...
end case

Ss
0
 
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
Yes, both are right. If you want the view only for grouping purposes, and nothing else, you won't need that; you can use ad-hoc views (aka derived tables)
select kmgroup, min(roadlength), max(roadlength), avg(roadlength)
from
 (select *, 
    case when roadlength <=  5 then 'group1'
         when roadlength <= 10 then 'group2'
         when roadlength <= 20 then 'group3'
         when roadlength <= 40 then 'group4'
         else 'group5'
    end kmgroup
  from kmtable
 ) grptbl
group by kmgroup

Open in new window

In addition this example shows that you won't need to use the between in case.
0
 
LowfatspreadCommented:
yes you can use a case statement to do this but you would be much better off if you actually set up
a table and used that in your view to give the grouping/range name
0
 
HRT_HSVAuthor Commented:
split points as first 2 comments provided the complete solution.  1st comment confirmed logic but 2nd comment had complete code.

Much appreciated everyone who provided solution thank you
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.