Question

in sql, i want to do something like

update table set col = rank(col) order by col

how do i do this ?

Purpose :

currently the col has extreme values, like -14000, 23, 4000, 23000 ... they are used in asc, desc sort but when i plot them on a slider, having say 10 positions, each slider position has highly uneven data, so to even it out i wish to renumber the column,

-14000 becomes 0
23 becomes 1
4000 becomes 2

and so on

Was it helpful?

Solution

Used this :

update table set col = (select count(*) from (select col from table) as temptable where temptable.col <table.col );

OTHER TIPS

In SQL Server, you can use two subqueries and the ROW_NUMBER function. In cases where you have duplicates in col, the ranking will follow standard competition ranking.

Sample script:

SELECT * INTO #TABLE
FROM
(
    select -14000 col
    union all SELECT 23
    union all select 4000
    union all SELECT 23 --sample duplicated data
) Unioned

UPDATE #TABLE
SET col =
(
    SELECT top 1 rowNum
    FROM
    (
        SELECT 
            col
            , row_number() OVER (order by col) - 1 rowNum --starts at 0 rank
        FROM #TABLE
    ) MySubQuery
    WHERE MySubQuery.col = #TABLE.col
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top