简体   繁体   English

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

[英]Oracle SQL Developer: How to transpose rows to columns using PIVOT function

I'm attempting to create a query to transpose rows into columns using the PIVOT function. 我正在尝试创建一个查询,使用PIVOT函数将行转换为列。

This is the contact table I want to transpose into rows: 这是我想要转换成行的contact表:

   PARTYID CONTACTTEXT  CONTACTTYPECD
---------- ------------ -------------
       100 0354441010               1
       100 0355551010               2
       100 0428105789               3
       100 abc@home.com             4

My intended result: 我的预期结果:

   PARTYID PHONE        FAX          MOBILE       EMAIL      
---------- ------------ ------------ ------------ ------------
       100 0354441010   0355551010   0428105789   abc@home.com

My query: 我的查询:

SELECT * FROM 
  ( 
    SELECT partyId, contacttext, contacttypecd 
    FROM CONTACT 
    WHERE partyId = 100; 
  ) 
  PIVOT ( 
    MAX(contacttext) 
  FOR contacttypecd in (1 Phone, 2 Fax, 3 Mobile, 4 Email)); 

Errors I'm getting: 我得到的错误:

Error starting at line 9 in command: 
FOR contacttypecd in (1 Phone, 2 Fax, 3 Mobile, 4 Email)) 
Error report: 
Unknown Command 

The reason for my problem was because my Oracle database version (Oracle9i) did not support the PIVOT function. 我的问题的原因是因为我的Oracle数据库版本(Oracle9i)不支持PIVOT功能。 Here's how to do it in a different way: 以下是以不同方式执行此操作的方法:

SELECT PartyCD
  ,MAX(DECODE(t.contacttypecd, 1, t.contacttext)) Phone
  ,MAX(DECODE(t.contacttypecd, 2, t.contacttext)) Fax
  ,MAX(DECODE(t.contacttypecd, 3, t.contacttext)) Mobile
  ,MAX(DECODE(t.contacttypecd, 4, t.contacttext)) Email
FROM 
  (
    SELECT partyid, contacttext, contacttypecd
    FROM CONTACT
    WHERE partyid = 100
  ) t
 GROUP BY PartyID

You have a stray semi-colon in your statement, after: 您的声明中有一个分散的分号:

    WHERE partyId = 100; 

Remove that to make it: 删除它使它:

SELECT * FROM 
  ( 
    SELECT partyId, contacttext, contacttypecd 
    FROM CONTACT 
    WHERE partyId = 100
  ) 
  PIVOT ( 
    MAX(contacttext) 
  FOR contacttypecd in (1 Phone, 2 Fax, 3 Mobile, 4 Email));

   PARTYID PHONE        FAX          MOBILE       EMAIL      
---------- ------------ ------------ ------------ ------------
       100 0354441010   0355551010   0428105789   abc@home.com

It's being seen as multiple statements; 它被视为多个陈述; the first is incomplete because it's missing a closing parenthesis (so gets ORA-00907), the second starts with that parenthesis and gets the error you reported, and then each subsequent line gets the same error. 第一个是不完整的,因为它缺少一个右括号(所以得到ORA-00907),第二个从括号开始并得到你报告的错误,然后每个后续行得到相同的错误。 You only seem to be looking at the last reported error - it's usually much more helpful to start with the first error, clear that, and then move onto the next if it still exists. 您似乎只是在查看上次报告的错误 - 从第一个错误开始通常更有帮助,清除它,然后移动到下一个错误(如果它仍然存在)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM