我的 Unpivot 查询结果的列不在我想要的位置

Columns of My Unpivot Query Results not Where I Want Them to Be

我编写了一个 SQL 查询,将 phone 数字从列在三个单独的列(Pri_Phn_No、Alt_Phn_No、Cell_Phn_No)中转换为一列 phone 数字和一列 phone 类型

问题是查询结果在phone数字和phone类型列之前显示DATE_CREATED和DATE_MODIFIED列。我希望它们在这些列之后显示。到目前为止,我尝试过的任何事情都没有奏效。

**如果我按我想要的顺序明确添加字段 - 到脚本的 Unpivot 部分:user_id、phone_type、phone_number、date_created , date_modified, 我收到以下错误信息

ORA-OO904: "date_modified": invalid identifier
00904. 0000 - "%s: invalid identifier"**

查询

CREATE Table UserPhoneNo nologging as

SELECT USER_ID, PRI_PHN_NO, ALT_PHN_NO, CELL_PHN_NO, DATE_CREATED, DATE_MODIFIED
FROM Address_history;

SELECT * FROM UserPhoneNo
UNPIVOT INCLUDE NULLS(
    (phone_number)  -- unpivot_clause
    FOR phone_type --  unpivot_for_clause
    IN ( -- unpivot_in_clause
        PRI_PHN_NO AS 'Primary', 
        ALT_PHN_NO AS 'Secondary', 
        CELL_PHN_NO AS 'Tertiary'
    )
)
order by USER_ID;

drop Table UserPhoneNo;

查询结果

示例查询数据

CREATE TABLE Address_History (
    USER_ID NUMBER(9) NOT NULL,
    PRI_PHN_NO VARCHAR2(50) NOT NULL,
    ALT_PHN_NO VARCHAR2(50) NULL,
    CELL_PHN_NO VARCHAR2(50) NULL,
    DATE_CREATED DATE NOT NULL,
    DATE_MODIFIED DATE NULL
);

Insert into Address_History 
(USER_ID,PRI_PHN_NO,ALT_PHN_NO,CELL_PHN_NO,DATE_CREATED,DATE_MODIFIED) values (475,'2191234567',2197654321,null,to_date('04-NOV-06','DD-MON-RR'),to_date('11-AUG-14','DD-MON-RR'));

Insert into Address_History
(USER_ID,PRI_PHN_NO,ALT_PHN_NO,CELL_PHN_NO,DATE_CREATED,DATE_MODIFIED) values (467,'3191234567',null,null,to_date('04-NOV-06','DD-MON-RR'),to_date('03-APR-08','DD-MON-RR'));

Insert into Address_History 
(USER_ID,PRI_PHN_NO,ALT_PHN_NO,CELL_PHN_NO,DATE_CREATED,DATE_MODIFIED) values (468,'4191234567',4197654321,null,to_date('04-NOV-06','DD-MON-RR'),null);

Insert into Address_History
 (USER_ID,PRI_PHN_NO,ALT_PHN_NO,CELL_PHN_NO,DATE_CREATED,DATE_MODIFIED) values (469,'5191234567',null,null,to_date('04-NOV-06','DD-MON-RR'),to_date('20-JAN-10','DD-MON-RR'));

Insert into Address_History 
(USER_ID,PRI_PHN_NO,ALT_PHN_NO,CELL_PHN_NO,DATE_CREATED,DATE_MODIFIED) values (471,'6191234567',null,null,to_date('04-NOV-06','DD-MON-RR'),to_date('19-MAY-08','DD-MON-RR'));

Insert into Address_History 
(USER_ID,PRI_PHN_NO,ALT_PHN_NO,CELL_PHN_NO,DATE_CREATED,DATE_MODIFIED) values (473,'7191234567',7197654321,null,to_date('04-NOV-06','DD-MON-RR'),to_date('20-JAN-10','DD-MON-RR'));

这是编写查询以查看所需列的正确方法:

SELECT USER_ID, phone_type, phone_number, DATE_CREATED, DATE_MODIFIED 来自 (SELECT USER_ID, PRI_PHN_NO, ALT_PHN_NO, CELL_PHN_NO, DATE_CREATED, DATE_MODIFIED 来自 Address_history)

逆枢轴包括空值(

phone_number -- unpivot_clause

对于 phone_type -- unpivot_for_clause

IN ( -- unpivot_in_clause

PRI_PHN_NO AS 'Primary', 

ALT_PHN_NO AS 'Secondary', 

CELL_PHN_NO AS 'Tertiary'

) )

按 USER_ID 排序;