x

Query a database to give a column(Position) for Ordinal Positions

I have a table having columns-
Id, Name, Sex and ScoresTotal.

I want to query it to insert a column Position whereby records 1st, 2nd, 3rd, 4th etc will automatically inserted based on ScoresTotal. That is, 1st should be inserted in the Position column for the the row with the highest ScoresTotal. 2nd for the next, etc.

Please help.

Thanks
more ▼

asked Apr 02, 2011 at 05:08 AM in Default

Fidell gravatar image

Fidell
11 1 1 1

(comments are locked)
10|1200 characters needed characters left

1 answer: sort voted first

Maybe, this will help:

SELECT *,RANK() OVER(ORDER BY ScoresTotal DESC) AS Rnk FROM yourtable

more ▼

answered Apr 02, 2011 at 07:32 AM

HelloFOFO gravatar image

HelloFOFO
106 2

Using rank() will allow holes in the numbers. For example, if there are 2 records with the same highest score then rank will assign number 1 to both, but the next score will get number 3. If this is not desired then dense_rank() could be used in place of rank(). This way both higest scores will get to be ranked 1 and the next will be ranked 2. If the holes in Position are acceptible then using the script in the answer does the trick.
Apr 02, 2011 at 07:15 PM Oleg
(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

New code box

There's a new way to format code on the site - the red speech bubble logo will automatically format T-SQL for you. The original code box is still there for XML, etc. More details here.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.

Topics:

x1949
x986
x7

asked: Apr 02, 2011 at 05:08 AM

Seen: 1333 times

Last Updated: Apr 03, 2011 at 06:49 AM