Update a column based on row_number()

Can picture Can · May 28, 2015 · Viewed 10.6k times · Source

i created a new not-null column with default value 0 for my table and it keeps display orders. I want to update all rows for that table, that displayorder has the value of row_number() over id ordered. here i can do this for one id. How can i do that for all ids.

my table is:

id | personid | name   | displayorder
---+----------+--------+------------
 1 |    10    | test1  |    0
 2 |    10    | test2  |    0
 3 |    10    | test3  |    0
 4 |    10    | test4  |    0
 5 |    10    | test5  |    0
 6 |    11    | test6  |    0
 7 |    11    | test7  |    0
 8 |    12    | test8  |    0

i want the result is:

id | personid | name   | displayorder
---+----------+--------+------------
 1 |    10    | test1  |    1
 2 |    10    | test2  |    2
 3 |    10    | test3  |    3
 4 |    10    | test4  |    4
 5 |    10    | test5  |    5
 6 |    11    | test6  |    1
 7 |    11    | test7  |    2
 8 |    12    | test8  |    1

here is my sql code, but it only works for just one given id:

update MyTable
set displayorder = z.ord
 FROM  (
   SELECT row_number() over (order by id) as ord, id 
     FROM MyTable p2
   where p2.personid = 1
   ) z
  where MyTable.id= z.id
  and personid = 1

Answer

Hell Boy picture Hell Boy · May 28, 2015

Use This Code:

 Create  TABLE #order
    (
        Id INT,
        PersonId INT,
        Name NVARCHAR(25),
        DisplayOrder INT
    )

    INSERT INTO #ORDER VALUES(1 , 10 , 'test1',0 )
    INSERT INTO #ORDER VALUES(2 , 10 , 'test2',0 )
    INSERT INTO #ORDER VALUES(3 , 10 , 'test3',0 )
    INSERT INTO #ORDER VALUES(4 , 10 , 'test4',0 )
    INSERT INTO #ORDER VALUES(5 , 10 , 'test5',0 )
    INSERT INTO #ORDER VALUES(6 , 11 , 'test6',0 )
    INSERT INTO #ORDER VALUES(7 , 11 , 'test7',0 )
    INSERT INTO #ORDER VALUES(8 , 12 , 'test8',0 )



 update #order 
    Set #order.DisplayOrder=R.DisplayOrder
    from(select id,ROW_NUMBER() over (partition by S.personid  order by S.id) as DisplayOrder
    from #order S) R
    where #order.Id=R.id

    select * from #order