读书人

求个高效率的计算库存的写法

发布时间: 2013-04-05 10:24:33 作者: rapoo

求个高效的计算库存的写法
本帖最后由 zzxap 于 2013-04-01 16:26:29 编辑 表1 进货和进货退货表innum是进货数量 flag=1 表示进货 flag=2表示退货 barcode 不唯一
productName,barcode,innum, flag
a aa 1000 1
a aa 32 2
a aa 500 1
a aa 3 2

表2 销售和销售退货表sellnum是销售或退货数量 flag=1 表示销售 flag=2表示销售退货 barcode 不唯一
productName,barcode,sellnum,flag
a aa 200 1
a aa 32 2
a aa 100 1
a aa 22 2

计算还剩下多少库存。两个表都很大


我写的,感觉结果不对
select i.barcode,ISNULL(sum(i.stocknum-j.sellnum),0) as stocknum from (
select top 30 a.productname,a.barcode,sum(CASE WHEN a.flag =1 THEN a.innum ELSE -a.innum END) as stocknum
from invoicing_Invoicing as a where a.userid=119
group by a.productname,a.barcode ORDER BY stocknum

)i left join ( select barcode ,sum(CASE WHEN flag =1 THEN sellnum ELSE -sellnum END) as sellnum from invoicing_sell where userid=119 group by barcode ) j on i.barcode=j.barcode

group by i.barcode ORDER BY stocknum


[解决办法]
说一下个人感觉:
表先建分区,按flag。
再按flag、productname汇总,合并出结果。
[解决办法]
select a.productName, a.barcode, sum((case when flag=2 then -1 else 1 end)*sellnum) from
(
select * from a
union all

select * from b
) a

group by a.productName, a.barcode


[解决办法]

--进货和退货 tb1
--销售和退货 tb2

select pname,bcode,sum(innum) as total_num
from(
select pname,bcode,innum from tb1 where flag = 1
union all
select pname,bcode,-innum from tb1 where flag = 2
union all
select pname,bcode,-innum from tb2 where flag = 1
union all
select pname,bcode,innum from tb2 where flag = 2
) t
group by pname,bcode

--这个是统计的方法,如果要高效的话建议可以使用视图!相关的索引要创建,减少表扫描的次数,或者可以利用临时表。

------解决方案--------------------


楼主这样的写法,OK

建一个覆盖索引,试试

读书人网 >SQL Server

热点推荐