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?
Requires Free Membership to View
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
- Dozens more answers to tough SQL questions from Rudy Limeback.
- The Best SQL Web Links: tips, tutorials, scripts, and more.
- Have an SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
- Ask your technical SQL questions -- or help out your peers by answering them -- in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, SQL Server, DB2, object-oriented and data warehousing gurus are waiting to answer your toughest questions.
This was first published in September 2003
Join the conversationComment
Share
Comments
Results
Contribute to the conversation