Problem solve Get help with specific problems with your technologies, process and projects.

Summing values in discrete ranges

I have a table that, among other columns, contain the columns:

id char(6) not null,
value double not null

I need to create a query that will count entries per value range grouped by id, something like:

id       <1.0     <2.0     <3.0     <4.0 
-------  -----    -----    -----    ----
AA00011    2        5        14      8
AA00239    3        1        23      5
AB00005    6        3        13      2

This database is in MySQL 4.0, which supports only limited subqueries in the where clause and does not have views. Is there any way to write this query in SQL?

Yes, there is. It's not always possible to work around the lack of support for subqueries, but in this case you can. In fact, I would do it this way even if subqueries were supported:

select id
     , sum( case when value < 1.0 
                 then 1
                 else 0  end )     as "<1.0"
     , sum( case when value >= 1.0 
                  and value < 2.0 
                 then 1
                 else 0  end )     as "<2.0"
     , sum( case when value >= 2.0 
                  and value < 3.0 
                 then 1
                 else 0  end )     as "<3.0"
     , sum( case when value >= 3.0 
                  and value < 4.0 
                 then 1
                 else 0  end )     as "<4.0"
  from thetable

Note that BETWEEN would not be right in this situation, as it includes the end points of the ranges.

For More Information

Dig Deeper on Oracle and SQL

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.