三张表,采购(a),付款(b) 合同表(c)采购表(a):
合同号   应付款
 1     10
 1     10
 2     20付款表(b):
合同号   实付款
 1     15
 2     10
 2     10
合同表(c)
合同号   欠款
1      5
2      0想得到的查询结果
合同号  应付款    实付款    欠款
 1    10     15       5
 1    10     []       []
 2    20     10       0
 2    []     10       []
[]表示空格

解决方案 »

  1.   


    create table 采购表
    (
    合同号 int,
    金额 int
    )
    go
    insert into 采购表
    select 1,10 union all
    select 1,10 union all
    select 2,20 
    go
    create table 付款表
    (
    合同号 int,
    [金额(付)] int
    )
    go
    insert into 付款表
    select 1,20 union all
    select 2,10 union all
    select 2,10 
    go
    create table 欠款表
    (
    合同号 int,
    欠款 int
    )
    go 
    insert into 欠款表
    select 1,5 union all
    select 2,0 
    go
    with tb1 as
    (
    select *,ROW_NUMBER() over(partition by 合同号 order by getdate()) as rk from 采购表 a
    )
    select 
    ISNULL(a.合同号,b.合同号) ,
    a.金额,
    b.[金额(付)],
    c.欠款
    from tb1 a
    full join 
    (
    select *,ROW_NUMBER() over(partition by 合同号 order by getdate()) as rk from 付款表 
    )b
    on a.合同号=b.合同号 and a.rk=b.rk
    full join
    (
    select *,ROW_NUMBER() over(partition by 合同号 order by getdate()) as rk from 欠款表  
    )c
    on a.合同号=c.合同号 and a.rk=c.rk
    /*
                金额          金额(付)       欠款
    ----------- ----------- ----------- -----------
    1           10          20          5
    1           10          NULL        NULL
    2           20          10          0
    2           NULL        10          NULL(4 row(s) affected)
    */