首页 > 解决方案 > 如何编写 SQL 以在一行中显示两列的不同值

问题描述

我有表a,b。表一

ID     In
----------------
1      Mat1
1      Mat2
2      Mat1
3      Mat3

表b

ID      Out
--------------
 1      Mat4
 2      Mat4
 2      Mat5
 3      Mat6

我想要一个像下面这样的结果。

ID     In    Out
------------------
 1    Mat1   Mat4
 1    Mat1
 2    Mat1   Mat4
 2           Mat5
 3    Mat3   Mat6

我认为完全加入不能在某些行中创建空字段。也许我需要为此使用 Rownum?有什么帮助吗?谢谢。

标签: sqlwindow-functionshanafull-outer-join

解决方案


一种选择是用于row_number()枚举行,然后full join是结果。为此,您需要在每个表中都有一个列来对记录进行排序。我假设ordering_id

select id, a.in, b.out
from (
    select a.*, row_number() over(partition by id order by ordering_id) rn 
    from tablea a
) a
full join (
    select b.*, row_number() over(partition by id order by ordering_id) rn 
    from tableb b
) b using(id, rn)

并非所有数据库都支持full join(并且并非所有数据库都支持using()连接条件)。

一种更便携的方法是使用union all

select id, max(in) in, max(out) out
from (
    select id, in, null out, row_number() over(partition by id order by ordering_id) rn 
    from tablea
    union all
    select id, null, out, row_number() over(partition by id order by ordering_id) rn 
    from tableb b
) x
group by id, rn

推荐阅读