SQL:更新一个字段,循环使用另一个字段的唯一值

发布于 2024-11-19 01:08:56 字数 336 浏览 3 评论 0原文

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

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

请,欢迎任何帮助!谢谢

I've a table with two fileds. I want to update ID_ELEM with a counter for each unique value of ID_TASS.
This should be the correct output table:

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

Please, any help is welcome! Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

你的背包 2024-11-26 01:08:56

我完全确定它是否会起作用:

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) 

I'm at all sure if it will work:

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

or maybe this:

UPDATE tbl
SET ID_ELEM = ROW_NUMBER() OVER (PARTITION BY ID_TASS) 
差↓一点笑了 2024-11-26 01:08:56

非常丑陋,但可以在 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

very ugly but works on 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
隔纱相望 2024-11-26 01:08:56

如果你想;

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

If you want;

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

You can (t-sql);

update tbl
    set ID_ELEM = (select COUNT(ID_TASS) from tbl where tbl.ID_TASS = T.ID_TASS)
from tbl T
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文