2015-12-08 31 views
1

我使用UNPIVOT创建了以下查询。它将列显示为我想要的行。我现在必须在2012年专栏中加入2013年专栏。这将是从mytable中选择的第二行。在未转换的情况下的Oracle数据透视表

我不知道如何做到这一点......无论是一个枢轴还是某种连接。

这是一个精简版,mytable有80列。

我的查询:

select value_type as " ", value as "2012" 
    from ((select to_char(id_internal) as "ID_INTERNAL", 
       to_char(tyear) as "YEAR", 
       to_char(transaction_id) as "TRANSACTION_ID", 
       to_char(in_date) as "IN_DATE", 
       to_char(name) as "NAME", 
       to_char(sid) as "SID", 
       to_char(address) as "ADDRESS", 
       to_char(city_state_zip) as "CITY_STATE_ZIP" 
      from mytable 
      where sid = 123456789 
      and tyear = 2012) 
     unpivot(value for value_type in (id_internal, 
           tyear, 
           transaction_id, 
           in_date, 
           name, 
           sid, 
           address, 
           city_state_zip))) 

所需的输出:

     2012       2013 
ID_INTERNAL   914008821991     914008821991 
TYEAR     2012       2013 
TRANSACTION_ID   64029620
IN_DATE    24-JAN-14     18-JAN-15 
NAME     BARBARA SMITH    BARBARA SMITH 
SID     123456789     123456789 
ADDRESS    123 Main Street    777 BIGSBY ST 
CITY_STATE_ZIP   GREENSBORO, NC 12345-1234 CHARLESTON, SC 12345-1234 

回答

0

就像你说的,你可以使用两年pivotself-join数据:

SQLFiddle

枢轴版本:

with t as (
    select * from (
    (select to_char(id_internal) as "C01_ID_INTERNAL", 
     to_char(tyear) as "TYEAR", 
     to_char(transaction_id) as "C02_TRANSACTION_ID", 
     to_char(in_date, 'yyyy-mm-dd') as "C03_IN_DATE", 
     to_char(name) as "C04_NAME", 
     to_char(sid) as "C05_SID", 
     to_char(address) as "C06_ADDRESS", 
     to_char(city_state_zip) as "C07_CITY_STATE_ZIP" 
    from mytable 
    where sid = 123456789 and tyear in (2012, 2013)) 
    unpivot (value for value_type 
     in (c01_id_internal, c02_transaction_id, c03_in_date, c04_name, 
      c05_sid, c06_address, c07_city_state_zip)))) 
select substr(value_type, 5) vt, yr_2012, yr_2013 
    from t pivot (max(value) for tyear in ('2012' yr_2012, '2013' yr_2013)) 
    order by value_type 

加入版本:

with t as (
    select * from (
    (select to_char(id_internal) as "C01_ID_INTERNAL", 
     to_char(tyear) as "TYEAR", 
     to_char(transaction_id) as "C02_TRANSACTION_ID", 
     to_char(in_date, 'yyyy-mm-dd') as "C03_IN_DATE", 
     to_char(name) as "C04_NAME", 
     to_char(sid) as "C05_SID", 
     to_char(address) as "C06_ADDRESS", 
     to_char(city_state_zip) as "C07_CITY_STATE_ZIP" 
    from mytable 
    where sid = 123456789 and tyear in (2012, 2013)) 
    unpivot (value for value_type 
     in (c01_id_internal, c02_transaction_id, c03_in_date, c04_name, 
      c05_sid, c06_address, c07_city_state_zip)))) 
select substr(value_type, 5) vt, t1.value v_2012, t2.value v_2013 
    from t t1 join (select * from t where tyear=2013) t2 using (value_type) 
    where t1.tyear = 2012 
+0

谢谢!这工作。 – Marianne

相关问题