SQL multiple column ordering

后端 未结 5 2198
梦谈多话
梦谈多话 2020-11-22 02:40

I am trying to sort by multiple columns in SQL, and in different directions. column1 would be sorted descending, and column2 ascending.

How

相关标签:
5条回答
  • 2020-11-22 03:20
    ORDER BY column1 DESC, column2
    

    This sorts everything by column1 (descending) first, and then by column2 (ascending, which is the default) whenever the column1 fields for two or more rows are equal.

    0 讨论(0)
  • 2020-11-22 03:23

    The other answers lack a concrete example, so here it goes:

    Given the following People table:

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

    If you execute the query below:

    SELECT * FROM People ORDER BY FirstName DESC, YearOfBirth ASC
    

    The result set will look like this:

     FirstName |  LastName   |  YearOfBirth
    ----------------------------------------
      Thomas   | More        |   1478
      Thomas   | Jefferson   |   1826
      Thomas   | Alva Edison |   1847
      Benjamin | Franklin    |   1706
    
    0 讨论(0)
  • 2020-11-22 03:28
    SELECT  *
    FROM    mytable
    ORDER BY
            column1 DESC, column2 ASC
    
    0 讨论(0)
  • 2020-11-22 03:35

    Multiple column ordering depends on both column's corresponding values: Here is my table example where are two columns named with Alphabets and Numbers and the values in these two columns are asc and desc orders.

    Now I perform Order By in these two columns by executing below command:

    Now again I insert new values in these two columns, where Alphabet value in ASC order:

    and the columns in Example table look like this. Now again perform the same operation:

    You can see the values in the first column are in desc order but second column is not in ASC order.

    0 讨论(0)
  • 2020-11-22 03:35

    You can use multiple ordering on multiple condition,

    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 
    
    0 讨论(0)
提交回复
热议问题