3

我有非连续但有序的数字标识符。我想获得连续的值。

当前表:

original_value

1
1
1
3
3
29
29
29
29
1203
1203
5230304
5230304
5230304
5230304

所需表:

original_value   desired_value

1                1
1                1
1                1
3                2
3                2
29               3
29               3
29               3
29               3
1203             4
1203             4
5230304          5
5230304          5
5230304          5
5230304          5
4

4 回答 4

3

另一种方法,无加入:

select

  original_value,
  case when @original = original_value then
    @group_number
  else
    @group_number := @group_number + 1
  end,
  (@original := original_value) as x

from tbl,(select @original := null, @group_number := 0) z
order by original_value

现场测试:http ://www.sqlfiddle.com/#!2/b82d6/6

如果要删除结果中的计算,请对查询进行表派生:

select w.original_value, w.group_number
from
(
  select

    original_value,
    case when @original = original_value then
      @group_number
    else
      @group_number := @group_number + 1      
    end as group_number,
    (@original := original_value) as x

  from tbl,(select @original := null, @group_number := 0) z
  order by original_value
) w

现场测试:http ://www.sqlfiddle.com/#!2/b82d6/4

于 2012-05-04T01:54:40.397 回答
2

汇总您的值,使用行号来获得您想要的值,然后加入您的原始值:

SELECT t.original, sq.desired
FROM Table t
INNER JOIN(
  SELECT ssq.original, @rownum:=@rownum+1 ‘desired’
  FROM (
    SELECT t.original
    FROM Table t
    GROUP BY t.original
    ORDER BY t.original
  ) ssq,
  (SELECT @rownum:=0) r 
) sq ON sq.original = t.original
于 2012-05-03T22:01:49.813 回答
1

还有另一种方法,这个模拟 DENSE_RANK 与连接:

    SELECT t.original, d.derived
      FROM t
INNER JOIN (    SELECT t.original, COUNT(DISTINCT t1.original) AS "derived"
                  FROM t
            INNER JOIN t t1
                       ON t.original >= t1.original
              GROUP BY 1) d
           ON t.original = d.original
  ORDER BY t.original;
于 2012-05-04T04:09:06.057 回答
0

如果我理解正确:

select 
    original_value, 
    dense_rank() over (order by original_value) as desired_value
于 2012-05-04T07:02:49.000 回答