根据组合分配新值

时间:2017-04-17 15:27:18

标签: sql oracle

我有这两个表

第一个有id和分类变量'代码' 表1

    id  code
1   1     F
2   1     B
3   1     J
4   2     D
5   2     B
6   2     F
7   2     G
8   2     C
9   2     D
10  3     G
11  3     G
12  3     G
13  4     B
14  4     F
15  4     C
16  4     D
17  5     C
18  5     A
19  5     G
20  5     D

和表2
有一些分类变量的组合'代码'为其分配了一个新类别' code3'

    code1 code2 code_3
1     C     B      O
2     B     A      K
3     A     C      L
4     E     B      N
5     A     D      J
6     D     B      L
table1中的

id包含多个代码,这些代码的组合产生在table2上找到的新代码。 如何根据表2中的组合,在table1中为表1中的值分配id?

期望的输出

会像

 id  code
1   1     F
2   1     B
3   1     J
5   2     L      -- added, while a B and D removed 
6   2     F
7   2     G
8   2     C
...

2 个答案:

答案 0 :(得分:2)

您可以通过自行加入然后加入prog.cc:16:11: error: implicit instantiation of undefined template 'TD<const int &>' TD<deref> td; ^ 来查找匹配项来获取要添加的新代码列表:

table2

答案 1 :(得分:1)

SELECT id, code, NVL (code3, code)
    FROM (SELECT id,
                 code,
                 hh,
                 rr,
                 gg,
                 code3
            FROM (  SELECT id,
                           code,
                           hh,
                           code || hh rr
                      FROM --here rr is used as foreign key which refer gg ,which can used as primary key of table2
                          (SELECT id,
                                  code,
                                  LEAD (code, 1, code)
                                     OVER (PARTITION BY id ORDER BY ROWNUM)
                                     hh
                             FROM table1)
                  ORDER BY code, hh) e, --hh gives the  code of next row of each code of table1
                 (  SELECT code1 || code2 gg, code3
                      FROM table2
                  ORDER BY code1, code2) b
           WHERE e.rr = b.gg(+))
ORDER BY id;                                                                                                                           --here left outer join is used to get desired output
    -- ORDER BY code,hh and ORDER BY code1,code2 are used to make sure that SUM(D+B)=L AND SUM(B+D)=L