5

Consider a table like

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

I need to generate a result set like this that debit come first and then ordered by code column:

debit   credit  code
----------------------------
5       0       1
6       0       2
5       0       3
7       0       6
0       15      1
0       11      2
0       10      5
Serkan Arslan
  • 13,158
  • 4
  • 29
  • 44
Elham Azadfar
  • 709
  • 2
  • 17
  • 34

4 Answers4

6

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
Serkan Arslan
  • 13,158
  • 4
  • 29
  • 44
3

Please use below one in order by clause you will get the output that you are looking for

  order by cast(cast(code as varchar(50)) 
                              + cast(debit as varchar(2)+ cast(credit as varchar(2) as int)
Rams
  • 2,129
  • 1
  • 12
  • 19
  • So `code` `5`, `debit` `11`, `credit` `2` would sort as equal to `5`, `1`, `12`. That doesn't sound right. – HABO Dec 24 '17 at 15:01
2
;WITH Props AS
(
SELECT *,
    ROW_NUMBER() OVER (ORDER BY c,cc) AS RowNumber
FROM Location

)
select * from Props order by d desc,RowNumber

Try the above code

WOrking fiddle here

Arijit Mukherjee
  • 3,817
  • 2
  • 31
  • 51
0

Use this select to help you:

SELECT debit, code, credit  
FROM table a
WHERE debit > 0
or debit = 0
order by debit  code, credit desc

or

SELECT debit, code, credit  
FROM table a
WHERE debit > 0
or debit = 0
group by debit, code, credit
order by debit  code, credit desc
Barr J
  • 10,636
  • 1
  • 28
  • 46