如何编写SQL以在一行中显示两列的不同值

问题描述

我有桌子a,b。 表a

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吗?有什么帮助吗?谢谢。

解决方法

一种选择是使用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