TSQL sorting issues

15431565 220 Reputation points
2023-08-30T08:55:52.23+00:00

Hello!

I know that order by can be used for sorting, and adding desc can be used to sort in descending order.

But now I need to move some of the last values to the middle, how do I do that?

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
10,904 questions
0 comments No comments
{count} votes

Accepted answer
  1. PercyTang-MSFT 8,981 Reputation points Microsoft Vendor
    2023-08-30T08:59:38.3333333+00:00

    Hi @15431565

    You can use the case when statement in the order by.

    Just like this.

    create table test(col int);
    insert into test values(4),(20),(36)
    select * from test order by case when col = 4 then 1
                                     when col = 20 then 3
    								 when col = 36 then 2 end;
    

    Output:

    User's image

    Best regards,

    Percy Tang

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful