鉴于:我有一个包含3列的表,即ID,MARKS和subject。
例如 -
表名(标记)
ID Marks Subject
323232 20
323232 10
323232 25
323232 2
对于主题栏,我们被要求从下表中更新
表名(主题)
ID Subject
323232 ENG
323232 SCI
323232 MAT
在这种情况下,我们需要更新Subject的主题栏,如下所示:
ID Marks Subject
323232 20 ENG
323232 10 SCI
323232 25 MAT
323232 2 ENG --- ONCE THE 3 DISTINCT VALUES ARE UPDATED WE MUST REPEAT UNTIL THE ID CHANGES.
我尝试使用while循环逻辑进行更新,但在更新MAT值后,我无法返回ENG。
让我知道这是否可以使用SQL查询实现。在此先感谢!!!
答案 0 :(得分:1)
我不确定你为什么想要,但你可以用模数运算来做到这一点:
with toupdate as (
select m.*,
row_number() over (partition by id order by (select null)) as seqnum
from marks m
),
t as (
select s.*, count(*) over (partition by id) as cnt,
row_number() over (partition by id order by (select null)) as seqnum
from subject s
)
update toupdate
from toupdate join
s
on toupdate.id = s.id and toupdate.seqnum % s.cnt = s.seqnum % s.cnt;