繁体   English   中英

按顺序更新列

[英]column update in sequence

我有一个包含3列的表,如下所示:

col1 col2 col3   
---- ---- ----
1     1   null
2     2   null
3     3   null
4     1   null
5     1   null
6     1   null
7     2   null
ETC

我需要更新同一表中的第三列,如下所示:

col1 col2 col3
---- ---- ----
1     1     1
2     2     1
3     3     1
4     1     2
5     1     3
6     1     4
7     2     4

更新背后的逻辑是,每当第二列中包含1时,第三列就必须递增。 第一列只是一个顺序整数列。

您可以使用row_number分析函数对col2 = 1的行进行顺序编号,然后使用子查询查找其他行的col1较低的最接近值。

因此,给出如下测试表:

create table t (c1 int, c2 int, c3 int);
insert t (c1, c2) values 
(1, 1),
(2, 2),
(3, 3),
(4, 1),
(5, 1),
(6, 1),
(7, 2);

这样的查询:

;with cte as (
    select t.c1, t.c2, x.c3 
    from t
    left join (
       select c1, c2, row_number() over (partition by c2 order by c1) c3 
       from t
       where c2 = 1 
    ) x on t.c1 = x.c1
)

update t 
set t.c3 = coalesce(cte1.c3,(select max(cte2.c3) from cte cte2 where cte2.c1 < cte1.c1))
from cte cte1
where t.c1 = cte1.c1

将给出以下结果:

c1  c2  c3
1   1   1
2   2   1
3   3   1
4   1   2
5   1   3
6   1   4
7   2   4

另一种可能更快的方法是:

update t1 set c3 = (select count(*) from t where c2 = 1 and c1 <= t1.c1) from t t1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM