连接Oracle中多个列的值

时间:2015-08-21 09:51:00

标签: sql oracle loops

我正在使用oracle数据库,我基本上需要在一列中连接,每行的多列值。

这样的事情:

col1    col2    col3    col4    col5
____________________________________
 1       A       B       C       D
 2       A       B       C
 3       C       A
 4       D       A       C

col1    col2
____________
 1      A,B,C,D
 2      A,B,C
 3      C,A
 4      D,A,C

4 个答案:

答案 0 :(得分:2)

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE test (col1, col2, col3, col4, col5 ) AS
          SELECT 1, 'A', 'B', 'C', 'D' FROM DUAL
UNION ALL SELECT 2, 'A', 'B', 'C', NULL FROM DUAL
UNION ALL SELECT 3, 'C', 'A', NULL, NULL FROM DUAL
UNION ALL SELECT 4, 'D', 'A', 'C', NULL FROM DUAL
UNION ALL SELECT 5, NULL, NULL, NULL, NULL FROM DUAL
UNION ALL SELECT 6, NULL, NULL, NULL, 'A' FROM DUAL
UNION ALL SELECT 7, 'B', NULL, NULL, 'A' FROM DUAL
UNION ALL SELECT 8, NULL, 'C', NULL, 'A' FROM DUAL;

查询1

如果其他值之间没有NULL值(它会在第7行和第8行引入多个逗号):

SELECT col1,
       TRIM( ',' FROM col2||','||col3||','||col4||','||col5 ) AS col2
FROM   test

<强> Results

| COL1 |    COL2 |
|------|---------|
|    1 | A,B,C,D |
|    2 |   A,B,C |
|    3 |     C,A |
|    4 |   D,A,C |
|    5 |  (null) |
|    6 |       A |
|    7 |   B,,,A |
|    8 |    C,,A |

最后两个查询适用于所有示例:

查询2

SELECT col1,
       TRIM( ',' FROM col2 || NVL2( col3, ','||col3, NULL ) || NVL2( col4, ','||col4, NULL ) || NVL2( col5, ','||col5, NULL ) ) AS col2
FROM   test

<强> Results

| COL1 |    COL2 |
|------|---------|
|    1 | A,B,C,D |
|    2 |   A,B,C |
|    3 |     C,A |
|    4 |   D,A,C |
|    5 |  (null) |
|    6 |       A |
|    7 |     B,A |
|    8 |     C,A |

查询3

SELECT col1,
       REGEXP_REPLACE( col2||','||col3||','||col4||','||col5, '(^|,),+|,+($)', '\1' ) AS col2
FROM   test

<强> Results

| COL1 |    COL2 |
|------|---------|
|    1 | A,B,C,D |
|    2 |   A,B,C |
|    3 |    C,A, |
|    4 |   D,A,C |
|    5 |  (null) |
|    6 |       A |
|    7 |     B,A |
|    8 |     C,A |

答案 1 :(得分:1)

使用以下查询

   select col1,rtrim( col2||','||col3||','||col4||','||col5,' ,') as col2  from table_name

答案 2 :(得分:0)

这可能是处理尾随逗号的更好方法,但这应该有效

SELECT col1, 
       col2 || decode(col3,'','',',') || col3 || decode(col4,'','',',') || col4 || decode(col5,'','',',')|| col5 as "col2"
  FROM table

答案 3 :(得分:0)

使用连接||

Select Col1|| ',' ||Col2|| ',' ||Col2|| ',' ||Col3|| ',' || Col4 As OneCol
From Table;