sql table sequence update help

Micke 21 Reputation points
2021-10-12T14:40:58.047+00:00

Hi,

I have a column named [list] which I need to update with sequence number partitioned by [id] order by [comment_timestamp]

It works in a select statement:
SELECT row_number() over (partition by id order by comment_timestamp)
FROM dbo.comments
but I don't know how to put this in an update statement?

The script for the table look like this
CREATE TABLE [dbo].[comments](
[id] [int] NOT NULL,
[list] [int] NULL,
[Comment] varchar NULL,
[domain] varchar NULL,
[comment_timestamp] datetime2 NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

I understand this might be very easy but could someone please assist? Appreciate all help

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,343 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,681 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 119.2K Reputation points
    2021-10-12T14:50:57.323+00:00

    Check this command:

    update t
    set list = rn
    from
    (
        select list, row_number() over (partition by id order by comment_timestamp) as rn
        from dbo.comments
    ) t
    

    If you are interested. you will also find an alternative based on "CTE".


1 additional answer

Sort by: Most helpful
  1. EchoLiu-MSFT 14,591 Reputation points
    2021-10-13T02:31:41.54+00:00

    Hi @Micke

    Welcome to the microsoft TSQL Q&A forum!

    Since window functions can only be used in SELECT or ORDER BY statements, you need to use subqueries or cte. The cte mentioned by Viorel-1 is as follows:

    ;WITH cte as  
    (SELECT [list],row_number() over (partition by id   
    order by comment_timestamp) rr   
    FROM [dbo].[comments])  
      
    UPDATE cte  
    SET [list]= rr  
    FROM cte  
    

    If you have any question, please feel free to let me know.
    If the response is helpful, please click "Accept Answer" and upvote it.

    Regards
    Echo


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


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.