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

多表关联

A 表(销售产品明细表)

ID 合同号 产品编号 单价 数量
1 111 1 2.0 50
2 111 2 5.0 150
3 111 3 3.0 500
4 112 1 2.0 50
5 112 2 3.0 50
6 113 1 2.0 50


B 表(销售回款表)  

ID 合同号 回款金额 回款日期
1 111 1500 2012-2-24
2 112 250 2012-3-4  
3 111 100 2012-4-2


C表(实际发货产品表)

ID 合同号 产品编号 单价 数量
1 111 1 2.0 50
2 111 2 5.0 100
4 112 1 2.0 50
5 112 2 3.0 50


现在要统计出已经发货的(在C表中存在的)但未全部回款的(A表中销售总价不等于B表中回款总金额)合同号

------解决方案--------------------
SQL code
select * from c left join b on b.hetonghao=c.hetonghao 
inner join a on a.hetonghao=b.hetonghao
where (a.danjia*b.shuliang) <>b.huikuanjine

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

select c.hetongNo
from c join (select hetongNo,sum(price*num) amount from a group by hetongNo) b on c.hetongNo = b.hetongNo
       join (select hetongNo,sum(reAmount) amount from b group by hetongNo) d on c.hetongNo = d.hetongNo
where b.amount <> c.amount
group by c.hetongNo

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

select distinct c.合同号 from c left join a on c.合同号=a.合同号 left join b on c.合同号=b.合同号
group by c.合同号
having sum(a.单价*数量)<>sum(b.回款金额)

------解决方案--------------------
这个错了,呵呵。
探讨
SQL code


select distinct c.合同号 from c left join a on c.合同号=a.合同号 left join b on c.合同号=b.合同号
group by c.合同号
having sum(a.单价*数量)<>sum(b.回款金额)

------解决方案--------------------
select distinct c.合同号
from a,b,c
where a.合同号=b.合同号
and b.合同号=c. 合同号
and b.回款金额 NOT (a.单价 * a.数量)
------解决方案--------------------
select distinct a.Contractno from A
where a.Contractno not in (
select d.Contractno(
(select b.Contractno,sum(b.price*b.num) as totalb from B b group by b.Contractno) d 
 left join (select c.Contractno,sum(c.backprice) as totalc from C c group by 
c.Contractno) e on e.Contractno = d.Contractno
where d.totalb=e.totalc
)