我的场景是,我必须通过在列quoteid和compid 的基础上对两个表a和B执行联接来将数据填充到表中
Table A
------------------------------
quoteid compid ................
10004 1
10004 1
10004 1
10004 22
10004 22
10004 22
Table B
------------------------------------
quoteid compid quartercode cost
10004 1 1q10 14
10004 1 2q09 10
10004 1 3q10 12
10004 22 4q12 32
10004 22 3q11 30
10004 22 2q11 43
现在,选择查询的结果应该像一样
quoteid compid quarter1cost quarter2cost quarter3cost
10004 1 10 14 12
10004 22 43 30 32
选择季度成本的概念是使用季度代码,该代码是一年中的季度(第一、第二…)和一年中最后两位数字的组合。所以,最古老的四分之一将是四分之一,第二古老的将是二分之一,最近的将是三分之一。在这里,由于加入条件的原因,只有最近3个季度的费用可用。例如,这里对于quoteid 10004和compid 1,quarter1将是2q09,quarter2将是1q10,quarter3将是3q10,因此成本。
我正试着用光标来做。但是由于我是新来的,所以无法得到想要的结果。
表A似乎与您的结果无关。
基本思想是使用row_number()
和条件聚合。这很复杂,因为四分之一标识符是向后存储的,因此无法正确排序。但你仍然可以做到:
select quoteid, compid,
max(case when seqnum = 1 then cost end) as cost_q1,
max(case when seqnum = 2 then cost end) as cost_q2,
max(case when seqnum = 3 then cost end) as cost_q3
from (select b.*,
row_number() over (partition by quoteid, compid
order by substr(quartercode, 1, 1), substr(quartercode, 3, 2)
) as seqnum
from b
) b
group by quoteid, compid