日期:2014-05-18 浏览次数:20792 次
declare @采购表 table([合同号] int,[应付款] int)
insert @采购表
select 1,10 union all
select 1,10 union all
select 2,20
declare @付款表 table([合同号] int,[实付款] int)
insert @付款表
select 1,15 union all
select 2,10 union all
select 2,10
declare @合同表 table([合同号] int,[欠款] int)
insert @合同表
select 1,5 union all
select 2,0
;with a as
(
select *,row_number() over (partition by [合同号] order by (select 1)) as id from @采购表
),b as
(
select *,row_number() over (partition by [合同号] order by (select 1)) as id from @付款表
),c as 
(
select *,row_number() over (partition by [合同号] order by (select 1)) as id from @合同表
)
select 
    isnull(a.合同号,b.合同号) as 合同号,
    isnull(ltrim(a.应付款),'[]') as 应付款,
    isnull(ltrim(b.[实付款]),'[]') as 实付款,
    isnull(ltrim(c.[欠款]),'[]') as 欠款
from  a 
full join  b on a.合同号=b.合同号 and a.id=b.id
full join  c on b.合同号=c.合同号 and b.id=c.id
order by 1,3 desc
/*
合同号         应付款          实付款          欠款
----------- ------------ ------------ ------------
1           10           15           5
1           10           []           []
2           20           10           0
2           []           10           []
*/
------解决方案--------------------
declare @采购表 table([合同号] int,[应付款] int)
insert @采购表
select 1,10 union all
select 1,10 union all
select 2,20
declare @付款表 table([合同号] int,[实付款] int)
insert @付款表
select 1,15 union all
select 2,10 union all
select 2,10
declare @合同表 table([合同号] int,[欠款] int)
insert @合同表
select 1,5 union all
select 2,0
;WITH t1 AS
(
    SELECT [合同号],[应付款],RN=ROW_NUMBER() OVER (PARTITION BY [合同号] ORDER BY GETDATE())
    FROM @采购表
),
t2 AS
(
    SELECT [合同号],[实付款],RN=ROW_NUMBER() OVER (PARTITION BY [合同号] ORDER BY GETDATE())
    FROM @付款表
),
t3 AS
(
    SELECT [合同号],[欠款],RN=ROW_NUMBER() OVER (PARTITION BY [合同号] ORDER BY GETDATE())
    FROM @合同表
)
SELECT CASE WHEN t1.合同号 IS NULL THEN t2.合同号
            ELSE t1.合同号 END 合同号,
            ISNULL(RTRIM(应付款),'') AS 应付款,
            ISNULL(RTRIM(实付款),'') AS 实付款,
            ISNULL(RTRIM(欠款),'') AS 欠款
FROM t1 FULL OUTER JOIN t2 ON t1.合同号 = t2.合同号 AND t1.RN = t2.RN
FULL OUTER JOIN t3 ON t2.合同号 = t3.合同号 AND  t2.RN = t3.RN
ORDER BY 合同号
合同号    应付款    实付款    欠款
1    10    15    5
1    10        
2    20    10    0
2        10