3

我订了桌子

  form_id | procedure_id 
----------+-------------
  101  |  24
  101  |  23
  101  |  22
  102  |  7
  102  |  6
  102  |  3
  102  |  2

另一张桌子已经表演了

form_id | procedure_id 
----------+-------------
  101  |  42
  101  |  45
  102  |  5
  102  |  3
  102  |  7
  102  |  12
  102  |  13

预期产出

form_id     o_procedure_id      p_procedure_id
  101           24                     42
  101           23                     45
  101           22                     NULL
  102           7                      7
  102           6                      5 
  102           3                      3 
  102           2                      12
  102           NULL                   13

我尝试了以下查询:

with ranked as
(select 
dense_rank() over (partition by po.form_id order by po.procedure_id) rn1,
dense_rank() over (partition by po.form_id order by pp.procedure_id) rn2,
po.form_id, 
po.procedure_id, 
pp.procedure_id
from ordered po, 
performed pp where po.form_id = pp.form_id)
select ranked.* from ranked 
--where rn1=1 or rn2=1

上述查询返回具有重复值排序和过程 ID 的值。如何获得例外输出?

4

1 回答 1

1

我不太确定您希望如何处理表格两侧的多个空值和/或空值。因此,我的示例假设第一个表处于领先地位并包含所有条目,而第二个表可能包含孔。查询并不漂亮,但我想它可以满足您的期望:

select test1_sub.form_id, test1_sub.process_id as pid_1, test2_sub.process_id as pid_2 from (
    select form_id, 
        process_id, 
        rank() over (partition by form_id order by process_id asc nulls last)
    from test1) as test1_sub
    left join (
        select * from (
            select form_id,
            process_id,
            rank() over (partition by form_id order by process_id asc nulls last)
        from test2
        ) as test2_nonexposed
    ) as test2_sub on test1_sub.form_id = test2_sub.form_id and test1_sub.rank = test2_sub.rank;
于 2013-04-16T19:17:02.733 回答