我有非连续但有序的数字标识符。我想得到连续的值。
当前表:
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
答案 0 :(得分: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
如果要删除result中的计算,table-派生查询:
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
答案 1 :(得分: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
答案 2 :(得分: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;
答案 3 :(得分:0)
如果我理解正确的话:
select
original_value,
dense_rank() over (order by original_value) as desired_value