Q:

Can a SQL query be run several times on different subsets of data?

I have a table that is just random values.
I have a query that looks something like this:
SELECT COUNT(DISTINCT(Value))
FROM RandomValueTable
WHERE
    Value > @lowerRange
AND
    Value < @upperRange

There will be a series of ranges I need to run this for (0-20, 21-45, 46-100 etc). Before running this query, I'll know what the ranges are. Do I need to run this query several times just filling in the range variables, or is there some way I can specify all the different ranges in one query?

A:

You can specify them in one query using group by:
select (case when value between 0 and 20 then '0-20'
             when value between 21 and 45 then '21-45'
             when value between 46 and 100 then '46-100'
             else 'other'
        end) as range,
       count(*)
from RandomValueTable
group by (case when value between 0 and 20 then '0-20'
               when value between 21 and 45 then '21-45'
               when value between 46 and 100 then '46-100'
               else 'other'
          end);

