【问题标题】:join two tables and pivot in oracle sql连接两个表并在 oracle sql 中进行透视
【发布时间】:2019-08-31 18:44:15
【问题描述】:

我需要连接两个表。

表 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 个月对应的第 2 季度,依此类推。

加入后,输出应该是:

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

【问题讨论】:

  • 选择4个表达式的查询如何返回17列的结果集?
  • 对不起...我的意思是输出应该以这种方式格式化...
  • qtr 是季度的第 3 个月,取值范围为 1 到 4,每个季度对应表 1 中的一行。表 2 为每月提交的列表。第 1 季度包括第 1 个月和第 2 个月(一月和二月),依此类推...

标签: sql oracle join


【解决方案1】:

你必须正确地加入季度和月份,例如floor((mo-1)/3) + 1 = qtr,这样你将一月、二月、三月分配到第一季度,四月、五月、六月到第二季度等等。像这里:

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

【讨论】:

  • 我可以在 plsql 中应用这个吗?
  • 可以,可以在PLSQL、代码块、过程、函数中使用SQL查询。
猜你喜欢
  • 2012-01-08
  • 2017-09-09
  • 2022-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多