距离上一篇《基于ACCESS和ASP的SQL多个表查询与计算统计代码(一)》竟然已经一年半的时间,明日复明日呀,借着这次写库存管理系统的机会,再总结一些ACCESS和ASP的SQL问题。此次总结的要点在于把查询(Select语句)作为表(AS语句)与表或查询再次进行Select的多表查询方法,逻辑上要很注意,非常容易把自己绕进去。
一、问题的提出
【出库和入库明细的Select语句,需要写出一个库存Select查询,包括A仓、B仓和分仓。】
二、解决入库、出库的统计
那么,首先Select Sum(入库数量),并Group By 产品编号,Having(入库仓库=A仓),可以形成一个对于A仓入库的统计表,【入库统计查询】代码及结果如下。
SELECT chanpin.ID AS 序号, chanpin.CPno AS 产品编号, chanpin.CPpinpai AS 产品品牌, chanpin.CPname AS 产品名称, chanpin.CPKind AS 产品规格, chanpin.CPunit as 计数单位, SUM(inck.INnum) AS 入库数量
FROM inck INNER JOIN chanpin ON inck.INcp = chanpin.CPno
GROUP BY chanpin.ID, chanpin.CPno, chanpin.CPpinpai, chanpin.CPname, chanpin.CPKind, chanpin.CPunit, inck.ToCK
HAVING(inck.ToCK='KJC-A')
此时若【入库统计查询】直接以左链(LEFT JOIN)将出库JOIN一起的话,会由于只能采用对应仓库的方式链接(ON 入库.仓库=出库.仓库)来链接,这样只会重复计算形成冗余,数据也是错误的,这并不是我需要的结果,如下看错误的测试:
SELECT chanpin.ID AS 序号, chanpin.CPno AS 产品编号, chanpin.CPpinpai AS 产品品牌, chanpin.CPname AS 产品名称, chanpin.CPKind AS 产品规格, chanpin.CPunit as 计数单位, SUM(inck.INnum) AS 入库数量, SUM(outck.OUTnum) as 出库数量
FROM (inck INNER JOIN chanpin ON inck.INcp = chanpin.CPno)
Left JOIN outck ON inck.ToCK=outck.FromCK
GROUP BY chanpin.ID, chanpin.CPno, chanpin.CPpinpai, chanpin.CPname, chanpin.CPKind, chanpin.CPunit, inck.ToCK
HAVING(inck.ToCK='KJC-A')
这是个错误的结果,从入库、出库明细来看,总入库、出库均重复计算了,数值当然是错误的。因此,不能简单的左链接来解决。
三、解决对入库出库的合并形成库存表
经过画简单的拓扑图,结论是应当把出库统计查询作为一个表来LEFT JOIN到入库统计查询里,此时对于链接的字段就不再是仓库了,而是已产品编号为链接字段,最后的结论及结果如下:
SELECT chanpin.ID AS 序号, chanpin.CPno AS 产品编号, chanpin.CPpinpai AS 产品品牌, chanpin.CPname AS 产品名称, chanpin.CPKind AS 产品规格, chanpin.CPunit as 计数单位, SUM(inck.INnum) AS 入库数量, IIF(AA.CC is not null,AA.CC,0) as 出库数量, 入库数量-出库数量 as 库存数量
FROM (inck INNER JOIN chanpin ON inck.INcp = chanpin.CPno)
left JOIN (select outck.outcp as BB, IIF(Sum(outck.OUTnum) is not null,Sum(outck.OUTnum),0) as CC From outck
GROUP BY outck.outcp, outck.FromCK HAVING(outck.FromCK='KJC-A')) as AA ON inck.INcp = AA.BB
GROUP BY chanpin.ID, chanpin.CPno, chanpin.CPpinpai, chanpin.CPname, chanpin.CPKind, chanpin.CPunit, inck.ToCK, AA.CC
HAVING(inck.ToCK='KJC-A')
LEFT JOIN()部分为出库统计查询,作为表左链接到入库统计查询里。
完成了A仓,同理可以完成B仓。