在SQL Query中显示连接值

时间:2018-02-16 22:22:52

标签: sql oracle oracle11g oracle11gr2 listagg

我想加入我的第一个sql查询,下面显示的表类型由id_pr value.ID_PR值重复。我想显示来自ident_st列的所有值与逗号分隔符连接的相同id_pr和rodz_st值。例如:显示rodz_st ='DZE'和id_pr = 13的所有ident_st值。

第一次查询:

SELECT NAME, NO FROM ORDERS o
LEFT JOIN TYPES t ON t.ID_ZM = o.ID_PR

表订单:

  ID        ID_ZM NAME    NO  
---------- ---------- ------- --------
    1        12   Dee     333
    2        13   Rods    111

表类型:

ID    ID_PR  RODZ_ST   IDENT_ST   
---------- ---------- ------- --------
16    12      JEW     646101_1
10    12      JEW     236496_2
11    13      JEW     147301_5
15    13      DZE     259435_1
12    13      OBR     452171_3
13    13      OBR     286432_6
17    12      DZE     618054_1
19    13      DZE     182235_4

我想要如下结果:

NAME    NO      JEW               DZE                  OBR
------- -----  ---------------- ------------------  -----------------
Dee     333   646101_1, 236496_2 618054_1
Rods    111   147301_5           259435_1, 182235_4 452171_3, 286432_6

问题:如何使用连接语句创建sql join以显示结果?

1 个答案:

答案 0 :(得分:3)

您可以使用LISTAGG列表DECODE功能:

SELECT NAME, NO, 
       LISTAGG(DECODE(RODZ_ST,'JEW',IDENT_ST,NULL), ',') WITHIN GROUP (ORDER BY t.ID DESC, RODZ_ST) AS JEWS,
       LISTAGG(DECODE(RODZ_ST,'DZE',IDENT_ST,NULL), ',') WITHIN GROUP (ORDER BY t.ID , RODZ_ST) AS DZE,
       LISTAGG(DECODE(RODZ_ST,'OBR',IDENT_ST,NULL), ',') WITHIN GROUP (ORDER BY t.ID , RODZ_ST) AS OBR
  FROM ORDERS o
   LEFT JOIN TYPES t ON t.ID_PR = o.ID_ZM
  GROUP BY NAME, NO;

SQL Fiddle Demo