0

I want to write an update script for the following table.

Id        int,
Title     nvarchar(100),
ProgramId int,
EventId   int,
SortOrder int

I want to set the SortOrder column to 1 through N, as sorted by the Id column. However, I want the number to restart when either ProgramId or EventId changes. That is, I'd like the numbering sequence 1...N for each row with the same ProgramId and EventId values, and then restart the numbering for the next ProgramId and EventId values.

I know I could use ROW_NUMBER to get a row number based on the current sorting, but I don't see how I could restart the number when one of those other two columns changes. Is this even possible?

4

1 回答 1

2

像这样:

;WITH cte As
(
    SELECT *,
        ROW_NUMBER() OVER (PARTITION BY ProgramId, EventId ORDER BY Id) As RN
    FROM   YourTable
)
UPDATE  cte
SET     SortOrder = RN
于 2013-04-30T06:16:27.103 回答