使用DB2

时间:2017-08-10 18:21:11

标签: sql db2

我正在DB2中使用SQL创建一个报告,我在其中一个表中有一个存储多个值的字段。现在,我需要引用另一个表来获取这些多个值的描述,如图所示。

表A

Item_No| R_code
---------------

 X       R01,R03,R04
 Y       R02,R03
 Z       R04

表B

R_code| Description
------------------

R01      Missing info
R02      Invalid info
R03      Invalid Account
R04      Missing Address

如果我加入表A和表B

,如何获得以下结果?

最终结果

Item_no| R_code     | Description
---------------------------

 X      R01,R03,R04  Missing info,Invalid Account,Missing Address
 Y      R02,R03      Invalid info,Invalid Account
 Z      R04          Missing Address

1 个答案:

答案 0 :(得分:0)

WITH unpivot (lvl, item_no, r_code, tail) AS (
  SELECT 1, item_no,
         CASE WHEN LOCATE(',',r_code) > 0 
              THEN TRIM(LEFT(r_code, LOCATE(',',r_code)-1))
              ELSE TRIM(r_code) 
        END,
         CASE WHEN LOCATE(',',r_code) > 0 
              THEN SUBSTR(r_code, LOCATE(',',r_code)+1)
              ELSE '' 
         END
  FROM tableA
  UNION ALL
  SELECT lvl + 1, item_no,
         CASE WHEN LOCATE(',', tail) > 0 
              THEN TRIM(LEFT(tail, LOCATE(',', tail)-1))
              ELSE TRIM(tail) 
         END,
         CASE WHEN LOCATE(',', tail) > 0 
              THEN SUBSTR(tail, LOCATE(',', tail)+1)
              ELSE '' 
         END
    FROM unpivot 
   WHERE lvl < 100 AND tail != ''),

get_desc AS
(
  SELECT item_no, up.r_code, tb.description
    FROM unpivot up
   INNER JOIN tableB tb
      ON up.item_no = tb.item_no
)

SELECT item_no,
       LISTAGG(r_code, ', ' ) WITHIN GROUP(ORDER BY r_code ASC) AS r_code,
       LISTAGG(description, ', ') WITHIN GROUP(ORDER BY description ASC) AS description
  FROM get_desc