oracle pl sql中如何将列数据转置为行

Posted

技术标签:

【中文标题】oracle pl sql中如何将列数据转置为行【英文标题】:How to transpose colums data into rows in oracle plsql 【发布时间】:2021-03-22 06:34:02 【问题描述】:

我的表如下:

MOBILE  ADDRESS_1   ADDRESS_2   ADDRESS_3   ADDRESS_TYPE
12345   ABC         EFG         HUJ         RS
12345   hjk         qqq         asd         OF
12345   jkh         sss         qwe         PR

我想要的输出是这样的:

MOBILE ADDRESS_1_RS ADDRESS_2_RS ADDRESS_3_RS  ADDRESS_1_OF ADDRESS_2_OF ADDRESS_3_OF ADDRESS_1_PR ADDRESS_2_PR ADDRESS_3_PR
12345  ABC          EFG          HUJ           hjk          qqq           asd          jkh         sss          qwe

【问题讨论】:

【参考方案1】:

您可以使用条件聚合来获得透视结果,例如

SELECT mobile,
       MAX(CASE WHEN address_type = 'RS' THEN address_1 END) AS "address_1_RS",
       MAX(CASE WHEN address_type = 'RS' THEN address_2 END) AS "address_2_RS",
       MAX(CASE WHEN address_type = 'RS' THEN address_3 END) AS "address_3_RS",

       MAX(CASE WHEN address_type = 'OF' THEN address_1 END) AS "address_1_OF",
       MAX(CASE WHEN address_type = 'OF' THEN address_2 END) AS "address_2_OF",
       MAX(CASE WHEN address_type = 'OF' THEN address_3 END) AS "address_3_OF",
       
       MAX(CASE WHEN address_type = 'PR' THEN address_1 END) AS "address_1_PR",
       MAX(CASE WHEN address_type = 'PR' THEN address_2 END) AS "address_2_PR",
       MAX(CASE WHEN address_type = 'PR' THEN address_3 END) AS "address_3_PR"              
  FROM t
 GROUP BY mobile 

Demo

【讨论】:

【参考方案2】:

您可以PIVOT:

SELECT mobile,
       rs_address_1 AS address_1_rs,
       rs_address_2 AS address_2_rs,
       rs_address_3 AS address_3_rs,
       of_address_1 AS address_1_of,
       of_address_2 AS address_2_of,
       of_address_3 AS address_3_of,
       pr_address_1 AS address_1_pr,
       pr_address_2 AS address_2_pr,
       pr_address_3 AS address_3_pr
FROM   table_name
PIVOT (
  MAX( address_1 ) AS address_1,
  MAX( address_2 ) AS address_2,
  MAX( address_3 ) AS address_3
  FOR address_type IN (
    'RS' AS rs,
    'OF' AS "OF",
    'PR' AS pr
  )
)

其中,对于您的示例数据:

CREATE TABLE table_name ( MOBILE, ADDRESS_1, ADDRESS_2, ADDRESS_3, ADDRESS_TYPE ) AS
SELECT 12345, 'ABC', 'EFG', 'HUJ', 'RS' FROM DUAL UNION ALL
SELECT 12345, 'hjk', 'qqq', 'asd', 'OF' FROM DUAL UNION ALL
SELECT 12345, 'jkh', 'sss', 'qwe', 'PR' FROM DUAL;

输出:

MOBILE | ADDRESS_1_RS | ADDRESS_2_RS | ADDRESS_3_RS | ADDRESS_1_OF | ADDRESS_2_OF | ADDRESS_3_OF | ADDRESS_1_PR | ADDRESS_2_PR | ADDRESS_3_PR
-----: | :----------- | :----------- | :----------- | :----------- | :----------- | :----------- | :----------- | :----------- | :-----------
 12345 | ABC          | EFG          | HUJ          | hjk          | qqq          | asd          | jkh          | sss          | qwe         

db小提琴here

【讨论】:

以上是关于oracle pl sql中如何将列数据转置为行的主要内容,如果未能解决你的问题,请参考以下文章

Oracle SQL Developer:如何使用 PIVOT 函数将行转置为列

Oracle:将列转置为行

将列转置为行 SQL Server

oracle如何在没有UNION的情况下将列转置为行

t-sql 将列转置为行

如何将列中的连接值转置为行