I have a simple table, but want to add a code so i can put a special result in a chosen position.
SELECT * FROM table ORDER BY rating DESC LIMIT 10;
I also have a column called position. If this has 4 as value i want it to show as the 4th result, if value is 7 as the 7th row and so on. Else I want it to order by rating.
Is this possible? With CASE maybe?
I tried the following
SELECT * FROM table
ORDER BY
CASE WHEN position = 4 THEN 4
WHEN position = 9 THEN 9
ELSE 0 END,
rating DESC
LIMIT 10;
This just hides those with values 4 and 9 in position.
SELECT * FROM table ORDER BY rating DESC LIMIT 10;
should give the following table
| Name | Rating | Position |
|---|---|---|
| Mike Brown | 93 | 0 |
| John Doe | 85 | 0 |
| Alex Johnson | 78 | 0 |
| Jane Smith | 72 | 0 |
| Emily White | 60 | 0 |
| Sarah Lee | 52 | 4 |
| Robert Miller | 49 | 0 |
| Emma Davis | 39 | 9 |
| David Clark | 38 | 0 |
| Olivia Hall | 30 | 0 |
I rather want a code to show following table
| Name | Rating | Position |
|---|---|---|
| Mike Brown | 93 | 0 |
| John Doe | 85 | 0 |
| Alex Johnson | 78 | 0 |
| Sarah Lee | 52 | 4 |
| Jane Smith | 72 | 0 |
| Emily White | 60 | 0 |
| Robert Miller | 49 | 0 |
| David Clark | 38 | 0 |
| Emma Davis | 39 | 9 |
| Olivia Hall | 30 | 0 |
I can get close (it's not perfect) by first setting a row-number based on the rating
Then I can use both that and the row number at the same level to determine the order:
The problem is it will lose a spot every time we do have a
positionmatch. Getting around this requires knowing how many rows have a setpositionvalue, so we can leave a place for them.