ORDER BY separately positive & negative numbers in MySQL statement

孤者浪人 提交于 2019-12-01 19:58:02

问题


I have a MySQL table and would like to return the rows based on a column value in this order:

  • First ascending order if the column >=0
  • Then descending order if the column <0

E.g. 0,2,4,7,-2,-3,-5


回答1:


Can use SIGN to sort the positive numbers to the top, then take the absolute value with ABS to get the desired ASC/DESC.

SELECT * FROM theTable
ORDER BY SIGN(col) DESC, ABS(col)

EDIT

As Nahuel pointed out, the above will sort 0's to the middle between positive and negative. To instead group them with the positives, you can use a CASE instead (or, if your column is only integers, the slightly magical SIGN(col + 1))

SELECT * FROM theTable
ORDER BY 
    CASE WHEN col >= 0 THEN 1 ELSE 2 END,
    ABS(col)



回答2:


SELECT columnName1 FROM Tbl
WHERE columnName1 >= 0
ORDER BY columnName1 ASC

UNION

SELECT columnName1 FROM Tbl
WHERE columnName1 < 0
ORDER BY columnName1 DESC

Should work



来源:https://stackoverflow.com/questions/11282571/order-by-separately-positive-negative-numbers-in-mysql-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!