有如下采购记录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请问如何实现??
采购单号 物料编号 采购数量
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请问如何实现??
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 行受影响)*/
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 '未交数量'
有如下采购记录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 ---(增加了这条多次收货记录)