单个查询中的多个数据范围SQL

时间:2017-10-27 11:56:08

标签: mysql sql

我现在有一个学生表我想编写一个查询,返回指定范围内的单个学生。例如,如果我提供两个范围(30到40)和(40到60),查询应该返回2个学生,一个在30到40范围内,一个在40到60范围内。 如何编写单个查询?

2 个答案:

答案 0 :(得分:2)

UNION

组合的where语句中使用两个具有不同范围的选择

示例:

(SELECT * FROM students WHERE ranges BETWEEN 30 AND 40 LIMIT 1)
UNION
(SELECT * FROM students WHERE ranges BETWEEN 40 AND 60 LIMIT 1)

答案 1 :(得分:0)

您可以使用OR条件:

(range between 30 and 40) OR (range between 40 and 60)

CASE

CASE WHEN range between 30 and 40 then 'X' else 'Y' as CLASS

然后您可以使用GROUP BY为类选择1条记录:

SELECT MAX(STUDENT_ID), CASE WHEN range between 30 and 40 then 'X' else 'Y' as CLASS
FROM MY_TABLE
GROUP BY CLASS