有如下采购记录tb_po
采购单号   物料编号  采购数量
P001       A-001     100
P002       A-001     300有如下收货记录tb_grn
收货单号   采购单号  物料编号  收货数量
G001       P001      A-001     120
G002       P002      A-001     200
我是这样算采购未交的:
select pno,
isnull((select sum(po_qty) from tb_po where pno=a.pno),0)-
isnull((select sum(in_qty) from tb_gr where pno=a.pno),0) as 采购未交
from tb_item a计算出来的结果是: 80
(100+300)-
120+200
而正确的结果要求是:100
100-120=-20=0  (负数为0)
300-200=100请问如何实现??

解决方案 »

  1.   

    create table tb_po(pno nvarchar(10),mid nvarchar(10),po_qty int)
    insert into tb_po select 'P001','A-001',100
    insert into tb_po select 'P002','A-001',300
    create table tb_grn(id nvarchar(10),pno nvarchar(10),mid nvarchar(10),in_qty int)
    insert into tb_grn select 'G001','P001','A-001',120
    insert into tb_grn select 'G002','P002','A-001',200
    go
    select sum(case when a.po_qty>b.in_qty then a.po_qty-b.in_qty else 0 end)
    from tb_po a inner join tb_grn b on a.pno=b.pno
    go
    drop table tb_po,tb_grn
    /*
    -----------
    100(1 行受影响)*/
      

  2.   

    有没有po 表中有而 grn 表中没有,或者po表中一个采购单号而 grn 表中有多个收货记录的情况呢?
      

  3.   

    select isnull((select sum(a.iCGSL) from tb_po a inner join tb_grn b on a.cCGDH=b.cCGDH and a.iCGSL>b.iSHSL),0)-
    isnull((select sum(b.iSHSL) from tb_po a inner join tb_grn b on a.cCGDH=b.cCGDH and b.iSHSL<a.iCGSL),0) as '未交数量'
      

  4.   

    1楼兄弟太好了,连创建数据表,及插入数据,以及最后删除创建的临时表都写好了,我只要复制代码就可以运行看结果了,这样的老师太好了,赞一个!1楼代码完全可以,不过有一种情况如2楼兄弟说的“一个采购单有多条收货记录”,这种情况怎么写SQL??
      

  5.   

    现在重新给出数据,主要是加了一张PO有多次送货情况,希望1楼的兄弟能再关注一个!!
    有如下采购记录tb_po
    采购单号 物料编号 采购数量
    P001 A-001 120
    P002 A-002 300        ---(改为不同物料)有如下收货记录tb_grn
    收货单号 采购单号 物料编号 收货数量
    G001 P001 A-001 100
    G002 P002 A-002 200
    G003 P001 A-001 50      ---(增加了这条多次收货记录)