0

I would like to add numbers to my rows based on the product value:

Lets say Ive got table:

ProductId Value
001 10
002 30
003 20

then when I order it by Value asc I would get:

ProductId Value
001 10
003 20
004 30

Now I want to add new column called Position and the result would be like this:

ProductId Value Position
001 10 1
002 30 3
003 20 2

Thanks for any help how can I do this.

My database serrver is sql server 2008R2

1
  • Your example still isnt congruent. You've now added a ProductId of 004 that doesnt fit in the previous or subsequent values. Commented Sep 7, 2014 at 17:21

2 Answers 2

3

You can use row_number

WITH T 
     AS (SELECT *, 
                ROW_NUMBER() 
                  OVER(ORDER BY ProductId) AS P 
         FROM   tablename) 
UPDATE T 
SET    Position = P 

Of course keeping this in synch following changes in the data may be hassle than it's worth if this is not a one off requirement.

Sign up to request clarification or add additional context in comments.

Comments

0

Ok so I figured out the answer: First add column: 'Position' and then:

Update A
SET A.Position = B.Position
from [Product] A join (
SELECT [ProductId]
      ,[Value]
      ,ROW_NUMBER() over (order by Value) as Position
  FROM Product)  B
  ON A.ProductId= B.ProductId

1 Comment

You don't need the join.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.