如何在SQL中按多个列和不同方向进行排序。column1将按降序排序,column2将按升序排序。


当前回答

通过DEPTNO ASC、JOB DESC从EMP订单中选择*;

其他回答

其他答案缺少一个具体的例子,因此如下:

给定以下人员表:

 FirstName |  LastName   |  YearOfBirth
----------------------------------------
  Thomas   | Alva Edison |   1847
  Benjamin | Franklin    |   1706
  Thomas   | More        |   1478
  Thomas   | Jefferson   |   1826

如果执行以下查询:

SELECT * FROM People ORDER BY FirstName DESC, YearOfBirth ASC

结果集将如下所示:

 FirstName |  LastName   |  YearOfBirth
----------------------------------------
  Thomas   | More        |   1478
  Thomas   | Jefferson   |   1826
  Thomas   | Alva Edison |   1847
  Benjamin | Franklin    |   1706
SELECT  *
FROM    mytable
ORDER BY
        column1 DESC, column2 ASC

您可以在多个条件下使用多个排序,

ORDER BY 
     (CASE 
        WHEN @AlphabetBy = 2  THEN [Drug Name]
      END) ASC,
    CASE 
        WHEN @TopBy = 1  THEN [Rx Count]
        WHEN @TopBy = 2  THEN [Cost]
        WHEN @TopBy = 3  THEN [Revenue]
    END DESC 

通过DEPTNO ASC、JOB DESC从EMP订单中选择*;

TRY

'select * FROM users ORDER BY id DESC, name ASC, age DESC