SQL Query to concatenate column values from multiple rows in Oracle

前端 未结 10 1236
鱼传尺愫
鱼传尺愫 2020-11-21 07:12

Would it be possible to construct SQL to concatenate column values from multiple rows?

The following is an example:

Table A

PID
A
B
C

10条回答
  •  醉话见心
    2020-11-21 07:13

    For those who must solve this problem using Oracle 9i (or earlier), you will probably need to use SYS_CONNECT_BY_PATH, since LISTAGG is not available.

    To answer the OP, the following query will display the PID from Table A and concatenate all the DESC columns from Table B:

    SELECT pid, SUBSTR (MAX (SYS_CONNECT_BY_PATH (description, ', ')), 3) all_descriptions
    FROM (
           SELECT ROW_NUMBER () OVER (PARTITION BY pid ORDER BY pid, seq) rnum, pid, description
           FROM (
                  SELECT a.pid, seq, description
                  FROM table_a a, table_b b
                  WHERE a.pid = b.pid(+)
                 )
          )
    START WITH rnum = 1
    CONNECT BY PRIOR rnum = rnum - 1 AND PRIOR pid = pid
    GROUP BY pid
    ORDER BY pid;
    

    There may also be instances where keys and values are all contained in one table. The following query can be used where there is no Table A, and only Table B exists:

    SELECT pid, SUBSTR (MAX (SYS_CONNECT_BY_PATH (description, ', ')), 3) all_descriptions
    FROM (
           SELECT ROW_NUMBER () OVER (PARTITION BY pid ORDER BY pid, seq) rnum, pid, description
           FROM (
                  SELECT pid, seq, description
                  FROM table_b
                 )
          )
    START WITH rnum = 1
    CONNECT BY PRIOR rnum = rnum - 1 AND PRIOR pid = pid
    GROUP BY pid
    ORDER BY pid;
    

    All values can be reordered as desired. Individual concatenated descriptions can be reordered in the PARTITION BY clause, and the list of PIDs can be reordered in the final ORDER BY clause.


    Alternately: there may be times when you want to concatenate all the values from an entire table into one row.

    The key idea here is using an artificial value for the group of descriptions to be concatenated.

    In the following query, the constant string '1' is used, but any value will work:

    SELECT SUBSTR (MAX (SYS_CONNECT_BY_PATH (description, ', ')), 3) all_descriptions
    FROM (
           SELECT ROW_NUMBER () OVER (PARTITION BY unique_id ORDER BY pid, seq) rnum, description
           FROM (
                  SELECT '1' unique_id, b.pid, b.seq, b.description
                  FROM table_b b
                 )
          )
    START WITH rnum = 1
    CONNECT BY PRIOR rnum = rnum - 1;
    

    Individual concatenated descriptions can be reordered in the PARTITION BY clause.

    Several other answers on this page have also mentioned this extremely helpful reference: https://oracle-base.com/articles/misc/string-aggregation-techniques

提交回复
热议问题