The question is: “How can I order by a sql statement using an if value?”
I have a table in which I have a parameters and using this parameters I have to order by ASC or DESC a single column. How can I achieve it?
I have understood that the ASC and DESC parameters cannot be in a IF block (and have a structure like this one. “IF(Type = ‘1’, ranking, ranking) ASC/DESC”), so which is the alternative to order inside a select in base to a parameters?
EXAMPLE
The table is something like:
ID | RANKING | TYPE
--------------------
1 | 12 | 1
2 | 10 | 1
3 | 14 | 2
4 | 15 | 2
The Type = 1 have to be an ASC order and the Type = 2 have to be a DESC order, so the expected result of my SELECT could be:
ID | RANKING | TYPE
--------------------
2 | 10 | 1
1 | 12 | 1
4 | 15 | 2
3 | 14 | 2
Any idea about it?
How about ordering by
IF(type=2, -ranking, ranking)after ordering by type? Negating the ranking will cause the opposite order for that type.EDIT
Since
rankingis aVARCHARcolumn, you would need to to convert it to a number to use this technique.You can test the code directly at sqlfiddle