I have a table that, among other columns, contain the columns:
By submitting your personal information, you agree that TechTarget and its partners may contact you regarding relevant content, products and special offers.
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
- 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.
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.