Order by x then order by y column in SQL Server

后端 未结 4 1134
忘掉有多难
忘掉有多难 2021-01-19 05:11

Consider a table like

   debit    credit  code
-----------------------------
    0       10      5
    5       0       3
    0       11      2
    0       15         


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-19 06:04

    You can use this.

    DECLARE  @MyTable TABLE(debit INT, credit INT,  code INT)
    
    INSERT INTO @MyTable VALUES 
    (0, 10, 5),
    (5, 0 , 3),
    (0, 11, 2),
    (0, 15, 1),
    (7, 0 , 6),
    (6, 0 , 2),
    (5, 0 , 1)
    
    SELECT * FROM 
        @MyTable 
    ORDER BY 
        (CASE WHEN debit > 0 THEN 0 ELSE 1 END) ,
        code , 
        debit
    

    Result:

    debit       credit      code
    ----------- ----------- -----------
    5           0           1
    6           0           2
    5           0           3
    7           0           6
    0           15          1
    0           11          2
    0           10          5
    

提交回复
热议问题