在该列的order by之后重新编号(将列设置为排名)

时间:2012-01-22 22:35:24

标签: mysql sql sql-order-by sql-update drizzle

在sql中,我想做类似

的事情
update table set col = rank(col) order by col

我该怎么做?

目的:

目前col有极值,如-14000,23,4000,23000 ......它们用于asc,desc排序但是当我在滑块上绘制它们时,说有10个位置,每个滑块位置都有很高的不均匀性数据,所以即使它我想重新编号列,

-14000 becomes 0
23 becomes 1
4000 becomes 2

等等

2 个答案:

答案 0 :(得分:2)

使用它:

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

答案 1 :(得分:0)

在SQL Server中,您可以使用两个子查询和ROW_NUMBER函数。如果您在col中有重复项,则排名将遵循standard competition ranking

示例脚本:

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
)