Behnam8
Behnam8

Reputation: 65

Custom ordering in SQL Server

I have a table like this:

Table_id   |   Name   |   Mark  | IDTable
-----------+----------+---------+------------
    1      |   John   |   12    |   NULL
    2      |   Alex   |   15    |   NULL
    3      |   Josh   |   11    |   NULL
    4      |   Merry  |   17    |    2
    5      |   Gary   |   13    |   NULL
    6      |   Jimmy  |   18    |    1

I want to sort the table to be like this:

Table_id   |   Name   |   Mark  | IDTable
-----------+----------+---------+------------
    1      |   John   |   12    |   NULL
    6      |   Jimmy  |   18    |    1
    2      |   Alex   |   15    |   NULL
    4      |   Merry  |   17    |    2
    3      |   Josh   |   11    |   NULL
    5      |   Gary   |   13    |   NULL

I mean, first try to sort by Table_ID, BUT if IDTable is equal to Table_id show it under that row.

Upvotes: 0

Views: 46

Answers (1)

HoneyBadger
HoneyBadger

Reputation: 15140

For your sample data COALESCE would work:

ORDER BY COALESCE(IDTable, Table_id )
,        IDTable

Upvotes: 4

Related Questions