UPDATE TABLE using ROW_NUMBER() OVER...
Hi Champs,
I am trying to either UPDATE or add a new column with ROWNUMBER() OVER an column on a table
table:
ID------Col2----Col3---
1-------12---------1
1-------34---------2
2-------44---------1
2-------75---------2
2-------77---------3
3-------23---------1
3-------33---------2
4-------44---------1
4-------22---------2I know I can get Col3 right with an SELECT and ROWNUMBER() OVER, but how can I UPDATE the table with the result?
/Many thanks
Answers
- You can use a CTE in any DML statement. So it is simpler to just do:with r_SomeTable
as
(
select *, row_number() over(partition by IDCol order by ValueCol) as rnk
from SomeTable
)
update r_SomeTable
set RANKCol = rnk
go
All Replies
- Hi,
here is a sample:
DROP
TABLE SomeTableGO
CREATE
TABLE SOmeTable(
IDCol
INT,ValueCol
INT,RANKCol
INT)
INSERT
INTO SomeTable VALUES(1,1,NULL)INSERT
INTO SomeTable VALUES(1,2,NULL)INSERT
INTO SomeTable VALUES(2,3,NULL)INSERT
INTO SomeTable VALUES(2,4,NULL)INSERT
INTO SomeTable VALUES(3,5,NULL)INSERT
INTO SomeTable VALUES(3,6,NULL)INSERT
INTO SomeTable VALUES(4,7,NULL)INSERT
INTO SomeTable VALUES(4,8,NULL)UPDATE
SomeTableSET
RankCol = SubQuery.RankFROM
(
SELECT IDCol, ValueCol, DENSE_RANK() OVER (PARTITION BY IDCOL ORDER BY ValueCOL) AS Rank FROM SomeTable)
SubQueryINNER
JOIN SomeTable ONSubQuery
.IDCol = SomeTable.IDColAND
SubQuery.ValueCol = SomeTable.ValueColSELECT
* From SomeTable
HTH, jens Suessmeyer.
---
http://www.sqlserver2005.de
--- Thank you!
- You can use a CTE in any DML statement. So it is simpler to just do:with r_SomeTable
as
(
select *, row_number() over(partition by IDCol order by ValueCol) as rnk
from SomeTable
)
update r_SomeTable
set RANKCol = rnk
go - Hi,
i have this tableID EXP Nation 11 2456 1 22 123 1 33 12556 1 44 23 2 and i need a query to ORDER me the table by EXP and to update the 1st ROW Nation = '1'
the 2'nd row mut be Nation = '2'
the 3'rd row Nation ='1'
the 4'th row Nation = '2'
and so on
I have 8000 rows and to edit it manualy take some time, i search for this problem 2 days but i dont finde a solution so i hope you can save some days from my life :))
Thx.
The resultat must be soID EXP Nation 33 12556 1 11 2456 2 22 123 1 44 23 2 From the top of my head - may need tweaking:
;with cte as (select ID, Exp, Nation, row_number() over (order by Exp Desc) as RowNum from myTable)
update cte set Nation = case RowNum % 2 = 1 then 1 else 2 end
Premature optimization is the root of all evil in programming. (c) by Donald Knuth
Naomi Nosonovsky, Sr. Programmer-Analyst
My blog

