2015-08-21 81 views
0

我正在使用一個oracle數據庫,並且我基本上需要在一列中進行連接,每行中有多個列的值。在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 
+0

您只有5列? – Crazy2crack

+0

不,我有45列。下一個問題應該是如何循環訪問列名! – petardms

回答

0

下面的查詢使用

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

rtrim在逗號之前使用一個空格! – Buddi

0

有可能的處理後面的逗號更好的辦法,但這應該工作

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

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 | 
0

使用連接||

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