0

I am developing an educational site with requires sorting by range of numbers. I need some help on how to sort my data into the range as listed below. 581 is the highest, 604 is the lowest. It starts with 604 to 582, and begin again with 1 until 581.

(Highest) 581 580 579.   .   . 3     2   1   582     .   .   .   602     603     604    (Lowest)

1 Answer 1

1

Here's one idea...

SELECT * FROM ints;
+---+
| i |
+---+
| 0 |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
+---+

SELECT i,CASE WHEN i < 5 THEN 1000-i ELSE i END x FROM ints ORDER BY x;
+---+------+
| i | x    |
+---+------+
| 5 |    5 |
| 6 |    6 |
| 7 |    7 |
| 8 |    8 |
| 9 |    9 |
| 4 |  996 |
| 3 |  997 |
| 2 |  998 |
| 1 |  999 |
| 0 | 1000 |
+---+------+

You can also write this as...

SELECT i FROM ints ORDER BY CASE WHEN i < 5 THEN 1000-i ELSE i END;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.