按x排序然后按SQL Server中的y列排序

Elh*_*far 5 sql t-sql sql-server

考虑像这样的表

   debit    credit  code
-----------------------------
    0       10      5
    5       0       3
    0       11      2
    0       15      1
    7       0       6
    6       0       2
    5       0       1
Run Code Online (Sandbox Code Playgroud)

我需要生成一个这样的结果集,首先是借记,然后按代码列排序:

debit   credit  code
----------------------------
5       0       1
6       0       2
5       0       3
7       0       6
0       15      1
0       11      2
0       10      5
Run Code Online (Sandbox Code Playgroud)

Ser*_*lan 7

你可以用它.

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
Run Code Online (Sandbox Code Playgroud)

结果:

debit       credit      code
----------- ----------- -----------
5           0           1
6           0           2
5           0           3
7           0           6
0           15          1
0           11          2
0           10          5
Run Code Online (Sandbox Code Playgroud)