简体   繁体   English

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

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

For the following data: 对于以下数据:

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

How can we sequentially read column data of PGM='First' and update into Columns of PGM='Second' 我们如何依次读取PGM ='First'的列数据并更新为PGM ='Second'的列

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

Here as we can see PGM='Second' has mapped the same data of PGM='First' for the 4 rows. 在这里,我们可以看到PGM ='Second'为4行映射了PGM ='First'的相同数据。 How can this be achieved in a single update query of such multiple records. 如何在这样的多个记录的单个更新查询中实现这一点。

Please guide. 请指导。

The basic idea is to use the row_number window function to assign 1, 2, 3 etc in order to the two sets. 基本思想是使用row_number窗口函数将1、2、3等分配给这两个集合。 You can then join these to figure out which value from set 1 should apply to which value in set 2. 然后,您可以将它们结合起来以找出集合1中的哪个值应应用于集合2中的哪个值。

Here's a lowest common denominator method that works on Postgres/Oracle/SQL Server. 这是可用于Postgres / Oracle / SQL Server的最低公分母方法。 I don't have access to DB2 to try it. 我没有访问DB2的权限。

if there aren't enough values in First, then the end values for second will be overwritten with null 如果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';

Example Fiddle 小提琴的例子

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

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