在oracle sql中将行数据转换为列数据

时间:2017-10-03 10:51:20

标签: sql oracle

例如:有一个列的表格中有common这样的数据,我想将其显示为

c
o
m
m
o
n

2 个答案:

答案 0 :(得分:1)

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE table_name( value ) AS
SELECT 'common' FROM DUAL UNION ALL
SELECT 'string' FROM DUAL;

查询1

SELECT REGEXP_REPLACE(
         value,
         '(.)',
         '\1' || CHR(10)
       )
FROM   table_name

<强> Results

| REGEXP_REPLACE(VALUE,'(.)','\1'||CHR(10)) |
|-------------------------------------------|
| c                                         |
| o                                         |
| m                                         |
| m                                         |
| o                                         |
| n                                         |
|                                           |
| s                                         |
| t                                         |
| r                                         |
| i                                         |
| n                                         |
| g                                         |
|                                           |

(如果需要,请使用TRIM删除尾随换行符。)

查询2

WITH characters ( value, character, lvl ) AS (
  SELECT value, SUBSTR( value, 1, 1 ), 1 FROM table_name
UNION ALL
  SELECT value, SUBSTR( value, lvl + 1, 1 ), lvl + 1
  FROM   characters
  WHERE  lvl < LENGTH( value )
)
SELECT character
FROM   characters
ORDER BY value, lvl

<强> Results

| CHARACTER |
|-----------|
|         c |
|         o |
|         m |
|         m |
|         o |
|         n |
|         s |
|         t |
|         r |
|         i |
|         n |
|         g |

答案 1 :(得分:0)

对于发布的样本数据,我们会这样做:

select substr(col1, level, 1)
from t23
connect by level <= length(col1)
/

如果您真正的需求更复杂,那么您必须发布一个真实的用例。如果您的表格中只有一行数据,那么MT0的recursive WITH clause solution就是可行的方式(假设你的数据是11gR2或更高)