sql多对多数据横向合并

img


怎么用sql实现这样把上面三张表的数据合并为一张表数据,实现多对多的的横向合并

用开窗函数,给主修和选修分组排个序号,然后再根据序号和学号来关联,比如


with t as (
select 1001 学号,'zs' 姓名),
t1 as (
select 1001 学号,'a' 主修科目 union all
select 1001 学号,'b' 主修科目 union all
select 1001 学号,'c' 主修科目 
),
t2 as (
select 1001 学号,'x1' 选修科目 union all
select 1001 学号,'x2' 选修科目
)
select t.学号,tx.主修科目,tx.选修科目 from t left join 
(
select isnull(t11.学号,t22.学号) 学号,主修科目,选修科目 from 
(select t1.*,row_number() over(partition by 学号 order by 主修科目) rn from t1) as t11
full join 
(select t2.*,row_number() over(partition by 学号 order by 选修科目) rn from t2) as t22
on t11.学号=t22.学号 and t11.rn=t22.rn
) as tx
on t.学号=tx.学号

img

用full join 的原因是,怕有人选修的科目比主修的还多

你要实现的效果是怎样的?