I have a student table now I want to write a query that return a single student in a specified ranges. For example if I provide two ranges (30 to 40) and (40 to 60), query should return me 2 students one which is in the range 30 to 40 and one in the range 40 to 60. How can I write a single query?
2 Answers
Use two selects with different ranges in where statement combined by UNION
Example:
(SELECT * FROM students WHERE ranges BETWEEN 30 AND 40 LIMIT 1)
UNION
(SELECT * FROM students WHERE ranges BETWEEN 40 AND 60 LIMIT 1)
4 Comments
pannu
What if we want to make the number of ranges configurable because in this solution we will have to write another select for every range.
Alex Kapustin
Yes, you have to build select for each range. There is no other way, afaik. But you can build dynamic sql, don't you ?
pannu
So we can take it as a sql query restriction.
pannu
Yes we can build on that thanks for pointing in the right direction it was really help full.
You can use OR condition:
(range between 30 and 40) OR (range between 40 and 60).
and CASE:
CASE WHEN range between 30 and 40 then 'X' else 'Y' as CLASS
and then you can use GROUP BY to select 1 record for class so:
SELECT MAX(STUDENT_ID), CASE WHEN range between 30 and 40 then 'X' else 'Y' as CLASS
FROM MY_TABLE
GROUP BY CLASS
5 Comments
pannu
but how to make sure we have single entry in the result for each Range
Alex Kapustin
So if there are 2 records in range 30-40 ? :)
NikNik
I was missing: "one which is in the range 30 to 40 and one in the range 40 to 60." I edited my question. @AlexKapustin
Alex Kapustin
Quite tricky solution :) and if there are no requirements to show more than 1 record from range could be solution. Well done @niknik
Neodan
The solution with UNION is more better and optimal, especially if you have a big amount of entries (-;
unionfor this