SQL连接和删除在两个单独的列中不同

SQL连接和删除在两个单独的列中不同

我订了桌子

  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

上面的查询返回的值具有repeat value ordered和procedure ID。
如何获得例外输出?

最佳答案

我不太确定您希望如何处理表两边的多个空值和/或空值。因此,我的示例假设第一个表是前导的,包含所有条目,而第二个表可能包含孔。查询并不漂亮,但我想它会按照您的预期:

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;

关于postgresql - SQL连接和删除在两个单独的列中不同,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14605436/

10-10 19:23