一列行中的多列值Oracle SQL [已关闭]

rkue9o1l  于 2023-05-16  发布在  Oracle
关注(0)|答案(3)|浏览(161)

已关闭,此问题需要details or clarity。目前不接受答复。
**想改善这个问题吗?**通过editing this post添加详细信息并澄清问题。

18小时前关闭
Improve this question
我已经得到了多个列的值,需要在结果区显示如下。在colNum列中,我需要连接每个结果的值
表名:测试
| 列编号|Col1| Col2| Col3|
| --------------|--------------|--------------|--------------|
| 1|一百二十三|三百四十一|六三五|
| 二|三百二十三|四三四|三百四十三|
结果
| 列编号|col123|
| --------------|--------------|
| 1-1-U|一百二十三|
| 1-2-U|三百四十一|
| 1-3-U|六百四十五|
| 2-1-U|三百二十三|
| 2-2-U|四三四|
| 2-3-U|三百四十三|
当我尝试unpivot得到下面的结果,但无法连接colNum中的附加值
结果
| 列编号|col123|
| --------------|--------------|
| 1|一个|
| 1| B|
| 1| c|

nkcskrwz

nkcskrwz1#

也许我误解了这个问题,但是-对我来说,它看起来像是3个选择的结合。
样本数据:

SQL> with test (colnum, col1, col2, col3) as
  2    (select 1, 'a', 'b', 'c' from dual union all
  3     select 2, 'x', 'y', 'z' from dual
  4    )

查询:

5  select colnum ||'-1-U' colnum, col1 col123
  6  from test
  7  union all
  8  select colnum ||'-2-U' colnum, col2
  9  from test
 10  union all
 11  select colnum ||'-3-U' colnum, col3
 12  from test
 13  order by 1;

COLNUM     COL123
---------- ----------
1-1-U      a
1-2-U      b
1-3-U      c
2-1-U      x
2-2-U      y
2-3-U      z

6 rows selected.

SQL>
oug3syen

oug3syen2#

你可以使用UNPIVOT子句:

SELECT colNum || '-' || col_code || '-U' as colNum, col123
FROM mytable
UNPIVOT(
    col123 
    FOR col_code
    IN (
        col1 AS '1', 
        col2 AS '2', 
        col3 AS '3'
    )
);

结果:

COLNUM  COL123
1-1-U   123
1-2-U   341
1-3-U   635
2-1-U   323
2-2-U   434
2-3-U   343

Demo here

z9smfwbn

z9smfwbn3#

你可以使用UNPIVOT和连接:

SELECT colNum || '-' || col || '-U' AS colNum,
       col123
FROM   table_name
       UNPIVOT(
         col123 FOR col IN (col1 AS 1, col2 AS 2, col3 AS 3)
       )

其中,对于样本数据:

CREATE TABLE table_name (colNum, Col1, Col2, Col3) AS
SELECT 1, 123, 341, 635 FROM DUAL UNION ALL
SELECT 2, 323, 434, 343 FROM DUAL;

输出:
| 栏目|COL123|
| --------------|--------------|
| 1-1-U|一百二十三|
| 1-2-U|三百四十一|
| 1-3-U|六三五|
| 2-1-U|三百二十三|
| 2-2-U|四三四|
| 2-3-U|三百四十三|
fiddle

相关问题