日期:2014-05-17 浏览次数:20501 次
我写的,感觉结果不对
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
--进货和退货 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
--这个是统计的方法,如果要高效的话建议可以使用视图!相关的索引要创建,减少表扫描的次数,或者可以利用临时表。