Dataset Sequence in SQL Server

I have a table of values ​​like this:

CREATE TABLE 
(
    Name1 VARCHAR (50),
    Name2 VARCHAR (50),
    Sequence INT
)

In this table, I have rows like this

'Bob', 'Jones', 1
'James','Ant', 2

I want the best thing to do is to perform an UPDATE (UPDATE SET) sequence based on the order of the Name2 column name, so when re-sequencing the values ​​are as follows:

'James','Ant', 1
'Bob', 'Jones', 2

I am sure that this can be done using the ROW_NUMBER OVER () CTE style, but I'm not sure about the exact syntax.

+3
source share
4 answers

How about something like this:

WITH OrderedByName AS
(
  SELECT Name1, Name2, 
  ROW_NUMBER() OVER(ORDER BY Name2, Name1) as 'RowNum'
  FROM YourTable
)
UPDATE YourTable
SET Sequence = obn.RowNum
FROM OrderedByName obn
WHERE obn.Name1 = YourTable.Name1 
  AND obn.Name2 = YourTable.Name2

Mark

+4
source

You can update CTE:

WITH OrderedT AS
(
  SELECT Sequence, 
  ROW_NUMBER() OVER (ORDER BY Name2, Name1) as rn
  FROM T
)
UPDATE OrderedT
SET Sequence = rn;
+6
source

CTE, , :

create table abc 
(
    Name1 VARCHAR (50),
    Name2 VARCHAR (50),
    Sequence INT
)

insert into abc values ('Bob', 'Jones', 1
)
insert into abc values ('James','Ant', 2
)

SELECT * FROM abc ORDER BY Sequence

UPDATE a
    SET Sequence=dt.Rank
    FROM abc a
        INNER JOIN (SELECT
                        Name1, Name2 
                            ,ROW_NUMBER() OVER(ORDER BY Name2, Name1,Sequence) AS Rank
                     FROM abc
                   ) dt ON a.Name1=dt.Name1 AND a.Name2=dt.Name2

SELECT * FROM abc ORDER BY Sequence

:

Name1               Name2    Sequence
------------------- -------- -----------
Bob                 Jones    1
James               Ant      2

(2 row(s) affected)

(2 row(s) affected)

Name1               Name2    Sequence
------------------- -------- -----------
James               Ant      1
Bob                 Jones    2

(2 row(s) affected)
+1

KM - MS SQL 2005 ROW_NUMBER().

0
source

Source: https://habr.com/ru/post/1719997/


All Articles