SQL:更新循环其他字段的唯一值的字段

时间:2011-07-07 11:14:27

标签: sql postgresql unique sql-update

我有一张有两个字段的桌子。我想使用计数器为ID_ELEM的每个唯一值更新ID_TASS。 这应该是正确的输出表:

ID_TASS, ID_ELEM   
1      , POL_1   
1      , POL_2   
1      , POL_3   
2      , POL_1   
2      , POL_2   
3      , POL_1   
4      , POL_1   
4      , POL_2   
4      , POL_3   
4      , POL_4

拜托,欢迎任何帮助!感谢

3 个答案:

答案 0 :(得分:1)

如果你想;

ID_TASS ID_ELEM
1       3
1       3
2       2
2       2
3       1
4       4
4       4
4       4
4       4
1       3

你可以(t-sql);

update tbl
    set ID_ELEM = (select COUNT(ID_TASS) from tbl where tbl.ID_TASS = T.ID_TASS)
from tbl T

答案 1 :(得分:1)

非常难看,但适用于mysql

SET @rank:=0;
update t1, (select id_tass, count(*) as c 
from t1
group by id_tass) T
set 
    t1.t1.id_elem = case  
    when @rank >= T.c then
    @rank:=0
    else  @rank
    end,
t1.id_elem = @rank:=@rank+1
where t1.id_tass = T.id_tass

答案 2 :(得分:1)

我完全相信它是否有效:

UPDATE tbl
SET ID_ELEM = rn
FROM
  ( SELECT ctid AS id
         , ROW_NUMBER() OVER (PARTITION BY ID_TASS) AS rn
    FROM tbl
  ) AS tmp
WHERE tbl.ctid = tmp.ctid

或者这个:

UPDATE tbl
SET ID_ELEM = ROW_NUMBER() OVER (PARTITION BY ID_TASS)