SQL reverse function

Lylyy 380 Reputation points
2023-09-22T07:12:25.6266667+00:00

Is there any function that reverse the whole column?

Sample like this:

User's image

Result:

User's image

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

Accepted answer
  1. LiHongMSFT-4306 26,706 Reputation points
    2023-09-22T07:20:22.14+00:00

    Hi @Lylyy

    As far as I know, there is not such function.

    If you want to access data from a previous row or next row, you might need LAG() or LEAD() function.

    Best regards,

    Cosmog Hong

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Yitzhak Khabinsky 25,851 Reputation points
    2023-09-22T14:49:17.0533333+00:00

    Hi @Lylyy,

    Please try the following.

    -- DDL and sample data population, start
    DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, [value] INT);
    INSERT @tbl ([value]) VALUES
    (111), (222), (333);
    -- DDL and sample data population, end
    
    -- before
    SELECT * FROM @tbl;
    
    -- after
    SELECT ROW_NUMBER() OVER (ORDER BY [value] DESC) AS ID
    	, [value]
    FROM @tbl;
    
    0 comments No comments

  2. Bruce (SqlWork.com) 64,161 Reputation points
    2023-09-22T15:50:55.95+00:00

    pretty simple set operation:

    update test 
        set value = t2.value
    from (
        select id, ROW_NUMBER() over (order by id) as rn
        from test
    ) t1
    join (
        select id, value, ROW_NUMBER() over (order by id desc) as rn
        from test
    ) t2 on t1.rn = t2.rn
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.