【问题标题】:assign a new value based on combinations根据组合分配新值
【发布时间】:2017-04-17 15:27:17
【问题描述】:

我有这两张表

第一个有 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

和table2
有一些分类变量“code”的组合,这些组合被分配了一个新的类别“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 上找到新代码。 如何根据它们的组合为table1中的id分配table2 code3中的值?

想要的输出

应该是这样的

 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
...

【问题讨论】:

  • 编辑您的问题并显示您想要的输出。

标签: sql oracle


【解决方案1】:

您可以通过自加入获取要添加的新代码列表,然后加入 table2 以查找匹配项:

select t1.id, t2.code3
from table1 t1 join
     table1 tt1
     on t1.id = tt1.id and
        t1.code < t2.code join
     table2 t2
     on t2.code1 = t1.code and
        t2.code2 = tt1.code;

【讨论】:

  • thanx for the solution ,正如@Stephano Zanini 指出的那样,最后一行应该是 t2.code2 = tt1.code;
  • @StefanoZanini 。 . .谢谢。
【解决方案2】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-08
    • 2016-09-06
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-05
    相关资源
    最近更新 更多