0

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?

4
  • use union for this Commented Oct 27, 2017 at 11:57
  • Please provide a sample data from student table. It is not clear if you have range in table and want just one record for each range or you have exact age or whatever value is in table Commented Oct 27, 2017 at 12:02
  • Lets say we have student id and percentage marks and I want to select a single student from each range, note that number of ranges may change they can be a parameter to the query. Commented Oct 27, 2017 at 12:04
  • Please dit your question and add some sample data and desired results for that data Commented Oct 27, 2017 at 12:08

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

4 Comments

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.
Yes, you have to build select for each range. There is no other way, afaik. But you can build dynamic sql, don't you ?
So we can take it as a sql query restriction.
Yes we can build on that thanks for pointing in the right direction it was really help full.
0

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

but how to make sure we have single entry in the result for each Range
So if there are 2 records in range 30-40 ? :)
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
Quite tricky solution :) and if there are no requirements to show more than 1 record from range could be solution. Well done @niknik
The solution with UNION is more better and optimal, especially if you have a big amount of entries (-;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.