Show concatenated values in SQL Query

走远了吗. 提交于 2019-12-14 02:11:49

问题


I want to join my first sql query with table Types showed below by id_pr value.ID_PR values are repeated. I want to show all values from ident_st column concatenated with comma separator for same id_pr and rodz_st values. For example: Show all ident_st values for rodz_st='DZE' and id_pr=13.

first query:

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

table Orders:

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

table Types:

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

I want result like below:

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

Question: How to create sql join with concatenated statement to get showed result?


回答1:


You may use list LISTAGG function with 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



来源:https://stackoverflow.com/questions/48835692/show-concatenated-values-in-sql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!