同时进行透视和交叉连接

时间:2018-05-20 01:09:55

标签: sql oracle oracle11g

我有两张桌子:

enter image description here

enter image description here

我试图构建一个返回的表:

enter image description here

其中:

 T3.VALUE_0M column is equal to T2.VALUE if:

 T2.OLD_DATE = T1.REF_DATE and T2.ID = T1.ID 

 or:

 T3.VALUE_0M is NULL if there is no T2.OLD_DATE = T1.REF_DATE. 


 T3.VALUE_1M column is equal to T2.VALUE if:    T1.OLD_DATE =
 ADD_MONTHS(T1.REF_DATE,-1) and T2.ID = T1.ID

 or:

 T3.VALUE_1M is NULL if there is no T2.OLD_DATE =
 ADD_MONTHS(T1.REF_DATE,-1).


 T3.VALUE_2M column is equal to T2.VALUE if:

 T1.OLD_DATE = ADD_MONTHS(T1.REF_DATE,-2) and T2.ID = T1.ID


 or:
 T3.VALUE_2M is NULL if there is no T2.OLD_DATE = ADD_MONTHS(T1.REF_DATE,-2).

等等。

我的挑战是:如果同一个T2.ID和T2.OLD_DATE有多个值,我想在不同的行中显示它们,但是要与其他VALUE列交叉。

我尝试过使用交叉联接,但结果并不理想:

enter image description here

可能是一个如此善良的人并帮我解决这些问题吗?

非常感谢!

1 个答案:

答案 0 :(得分:0)

根据我的理解,生成的查询将如下所示:

SELECT t1.ID, t2.ref_date, 
       (case when ( T1.OLD_DATE = T2.REF_DATE and T2.ID = T1.ID )
       then t1.value end) value_0m,       
       (case when ( T1.OLD_DATE = ADD_MONTHS(T2.REF_DATE,-1) and T2.ID = T1.ID  )        
       then t1.value end) value_1m,
       (case when ( T1.OLD_DATE = ADD_MONTHS(T2.REF_DATE,-2) and T2.ID = T1.ID  )
       then t1.value end) value_2m,
       (case when ( T1.OLD_DATE = ADD_MONTHS(T2.REF_DATE,-3) and T2.ID = T1.ID  )
       then t1.value 
       end) value_3m       
  FROM T1 CROSS JOIN T2;

SQL Fiddle Demo