2012-05-03 93 views
3

我有非連續但有序的數字標識符。我想獲得連續的值。SQL:用連續值替換非連續值

當前表:

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 
+1

你想要一個顯示連續值的查詢,還是想用連續值更新當前值? – Bohemian

回答

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

2

總結自己的價值觀,用行號以獲得您想要的值,然後再加入回原來的值:

SELECT t.original, sq.desired 
FROM Table t 
INNER JOIN(
    SELECT ssq.original, @rownum:[email protected]+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 
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; 
+0

看到這篇文章爲什麼從一開始'重新'COUNT'是壞的http://sqlblog.com/blogs/adam_machanic/archive/2006/07/12/running-sums-redux.aspx –

+0

@MichaelBuen,是的,這答案僅僅是正確的,而不是正確和有效的。 :) – pilcrow

+0

您建議您自己也將在生產中使用的答案?是嗎? ;-) –

0

如果我理解正確的話:

select 
    original_value, 
    dense_rank() over (order by original_value) as desired_value 
+0

+1爲最好的技術,但-1,因爲MySQL不支持這一點。 :) – pilcrow