日期:2014-05-18  浏览次数:20656 次

非专业新手求教
遇到个作业题,没想通怎么实现,请大侠们帮看一下,谢谢。


三张表,采购(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       []
[]表示空格


select a.合同号,a.应付款,b.实付款,c.欠款
from a ,b,c 
where a.合同号=b.合同号and a.合同号=c.合同号
这样写的话,查询结果始终不会有空值,加入distinct呢,又变2行了。

------解决方案--------------------
原来这三个表没有主键...

SQL code

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           []
*/

------解决方案--------------------
SQL code

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