Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/oracle/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在oracle sql中联接两个表和透视_Sql_Oracle_Join - Fatal编程技术网

在oracle sql中联接两个表和透视

在oracle sql中联接两个表和透视,sql,oracle,join,Sql,Oracle,Join,我需要把两张桌子连接起来 表1包含季度清单,并包含以下列: Year, ID, ID2, Quarter(value can be 1, 2, 3, 4), Amount_Due_for_the_Quarter 2018, 001, 000, 3, $1.00 2018, 001, 000, 4, $2.000 Year, ID, ID2, Mo (value is from January[1] to December[12]), Amount_Due_ per_Month 2018, 00

我需要把两张桌子连接起来

表1包含季度清单,并包含以下列:

Year, ID, ID2, Quarter(value can be 1, 2, 3, 4), Amount_Due_for_the_Quarter
2018, 001, 000, 3, $1.00
2018, 001, 000, 4, $2.000
Year, ID, ID2, Mo (value is from January[1] to December[12]), Amount_Due_ per_Month
2018, 001,000, 8, $5.00
2018, 001,000, 10, $6.00
2018, 001,000, 11, $7.00
表2包含每月提交的清单,并包含以下列:

Year, ID, ID2, Quarter(value can be 1, 2, 3, 4), Amount_Due_for_the_Quarter
2018, 001, 000, 3, $1.00
2018, 001, 000, 4, $2.000
Year, ID, ID2, Mo (value is from January[1] to December[12]), Amount_Due_ per_Month
2018, 001,000, 8, $5.00
2018, 001,000, 10, $6.00
2018, 001,000, 11, $7.00
这些表可以使用ID、ID2和year进行联接。第一个表可能有也可能没有所有季度的提交。第二个表可能有也可能没有所有月份的提交。第一季度对应于第1个月、第2个月、第4个月和第5个月的第二季度,依此类推

联接后,输出应为:

Year, ID, ID2, Quarter, Amount Due for Qtr, jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec
2018, 000, 001, 3, $1, null, null, null, null, null, null, null, $5.00, null, null, null, null
2018, 000, 001, 4, $2, null, null, null, null, null, null, null, null, null, $6.00, $7.00, null




select
      a.qtr,
      b.id,
      b.id2,
      nvl(b.Amount_Due_ per_Month,0)
from  tbl1  a
      left join tbl2 b
        on a.year = b.year
        and a.id = b.id
        and a.id2 = b.id2
  where a.year = '&year'
        and a.id = '&id'
        and a.id2 = '&id2';
但是给了我:

Year, ID, ID2, Quarter, Amount Due for Qtr, jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec
2018, 000, 001, 3, $1, null, null, null, null, null, null, null, $5.00, null, $6.00, $7.00, null
2018, 000, 001, 4, null, null, null, null, null, null, null, null, null, null, $6.00, $7.00, null

您必须正确地加入季度和月份,例如使用
楼层((mo-1)/3)+1=qtr
,这样您可以将1月、2月、3月分配到季度1、4月、5月、6月分配到季度2等,如下所示:

select * 
  from (
    select * from t1 
      join t2 using (year, id, id2) 
      where id = '001' and id2 = '000' and floor((mo-1)/3) + 1 = qtr)
  pivot (max(amt_mth) for mo in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))

选择4个表达式的查询如何返回包含17列的结果集?抱歉。。。我的意思是输出的格式应该是这样的……qtr是一个季度的第三个月,可以有1到4的值,每个季度对应于表1中的一行。表2是每月提交的清单。第1季度包括第1个月和第2个月(1月和2月),等等……我可以在plsql中应用这个吗?是的,您可以在plsql、代码块、过程和函数中使用SQL查询。