连接两个表并在Oracle SQL中进行数据透视

时间:2019-04-10 10:31:26

标签: 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

表2包含每月提交的列表,并包含以下列:

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和年份进行联接。第一表可能会也可能不会所有季度都提交。第二个表格可能在所有月份中都可以提交,也可以不提交。第1季度对应于第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

1 个答案:

答案 0 :(得分:1)

您必须正确地加入季度和月份,例如使用floor((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))

dbfiddle demo