繁体   English   中英

使用从同一表的多行检索的数据更新多列

[英]Update multiple columns with data retrieved from multiple rows of same table

对于以下数据:

PGM      INC        EXC
First    A          AA
First    B          BB
First    C          CC
First    D          DD

Second   E          EE
Second   F          FF
Second   G          GG
Second   H          HH

我们如何依次读取PGM ='First'的列数据并更新为PGM ='Second'的列

PGM      INC        EXC
Second   E          AA
Second   F          BB
Second   G          CC
Second   H          DD

在这里,我们可以看到PGM ='Second'为4行映射了PGM ='First'的相同数据。 如何在这样的多个记录的单个更新查询中实现这一点。

请指导。

基本思想是使用row_number窗口函数将1、2、3等分配给这两个集合。 然后,您可以将它们结合起来以找出集合1中的哪个值应应用于集合2中的哪个值。

这是可用于Postgres / Oracle / SQL Server的最低公分母方法。 我没有访问DB2的权限。

如果First中的值不足,则second的最终值将被null覆盖。

Update
    test
Set
    Exc = (
        Select
            f.Exc
        From (
            Select
                Exc,
                row_number() over (order by inc) as rn
            From
                test
            Where
                Pgm = 'First'
        ) as f
        inner join (
            Select
                Inc,
                row_number() over (order by inc) as rn
            From
                test
            Where
                Pgm = 'Second'
        ) as s
            On f.rn = s.rn
        Where
             test.inc = s.inc
    )
Where
    test.Pgm = 'Second';

小提琴的例子

暂无
暂无

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

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