程橙子不酸u 2022-03-22 10:40 采纳率: 0%
浏览 70

sql多对多数据横向合并

img


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

  • 写回答

2条回答 默认 最新

  • DarkAthena ORACLE应用及数据库设计方案咨询师 2022-03-22 17:21
    关注

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

    
    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 的原因是,怕有人选修的科目比主修的还多

    评论

报告相同问题?

问题事件

  • 创建了问题 3月22日