发布时间:2011-08-23 09:45 来源:未知
SQL Server数据库多表关联汇总查询是我们经常用到的,本文我们就介绍了一个多表关联汇总查询的实例,通过这个实例在多表关联查询中遇到的问题以及它的解决方法让我们一起来了解一下SQL Server数据库多表关联汇总查询的相关知识吧,希望本次的介绍能够对您有所帮助。
select isnull(s.mnumber,ss.mnumber) mnumber,isnull(m.whcode,ss.whcode) whcode, isnull(sum(factreceiptquan),0)-isnull(sum(factissuequan),0) + sum(isnull(ss.quan,0)) quan from (select * from gy_inoutmain where billcode in('1201','1202','1203','1204','1205','1206') ) m inner join gy_inoutsub s on m.inoutmainid=s.inoutmainid left join( select sms.mnumber,sm.whcode,sum(sms.quan) quan from Kf_StartMain sm inner join Kf_Startsub sms on sm.startmainid=sms.startmainid group by sm.whcode,sms.mnumber ) ss on m.whcode=ss.whcode and s.mnumber=ss.mnumber group by isnull(m.whcode,ss.whcode),isnull(s.mnumber,ss.mnumber) order by s.mnumber
上面将收发表的数量进行汇总,然后再加上期初表的数量,得到库存量。但是得到的实际数量却多出很多来,比如本来物料“010101004”只有20吨,统计的结果却有5000多吨。问题出在哪里呢?
select sms.mnumber,sm.whcode,sum(sms.quan) quan from Kf_StartMain sm inner join Kf_Startsub sms on sm.startmainid=sms.startmainid where sms.mnumber='010101004 ' group by sm.whcode,sms.mnumber
上面sql统计[期初表] 数量 = 31.500000
select s.mnumber,m.whcode, isnull(sum(factreceiptquan),0)-isnull(sum(factissuequan),0) quan from (select * from gy_inoutmain where billcode in('1201','1202','1203','1204','1205','1206') ) m inner join gy_inoutsub s on m.inoutmainid=s.inoutmainid where s.mnumber='010101004 ' group by m.whcode,s.mnumber order by s.mnumber
上面sql统计[收发表] 数量 = -27.000000
select s.mnumber,m.whcode, isnull(sum(factreceiptquan),0)-isnull(sum(factissuequan),0) +sum(ss.quan) quan from (select * from gy_inoutmain where billcode in('1201','1202','1203','1204','1205','1206') ) m inner join gy_inoutsub s on m.inoutmainid=s.inoutmainid left join( select sms.mnumber,sm.whcode,sum(sms.quan) quan from Kf_StartMain sm inner join Kf_Startsub sms on sm.startmainid=sms.startmainid where sms.mnumber='010101004 ' group by sm.whcode,sms.mnumber ) ss on m.whcode=ss.whcode and s.mnumber=ss.mnumber where s.mnumber='010101004 ' group by m.whcode,s.mnumber order by s.mnumber
上面sql关联两表,数量=57145.500000,原来,在[收发表]关联[期初表],[收发表]有几百条记录,而[期初表]只有一条记录,两者一关联,则这几百条记录都有期初数,结果期初数被累加了几百次。
举个例子:
create table [期初表](MNUmber varchar(10),quan decimal(10,3)) create table [收发表](MNUmber varchar(10),quan decimal(10,3)) insert into [期初表] values('001',7) insert into [期初表] values('001',5) insert into [期初表] values('001',-9) insert into [收发表] values('001',10) select sum(quan) from 期初表 --期初表合计=3
那得到的现存量应该是 [收发表]的合计 加上 期初数:3+10 = 13。但一关联,再汇总,就出问题了。
select sum(m.Quan)+sum(s.Quan) from [收发表] m inner join [期初表] s on m.MNumber=s.MNumber group by m.MNumber
得到的结果是33。因为一关联,就变成:
收发表.MNumber 收发表.quan 期初表.MNumber 期初表.quan --------------------------------------------------------------------- 001 7 001 10 001 5 001 10 001 -9 001 10
结果就变成:7+5+(-9)+10+10+10,期初数被加了三次。解决的办法就是采用平级汇总的方式,先汇总,然后再关联。不要关联的两边,一边是明细,一边是汇总,那关联肯定出问题。
关于SQL Server数据库多表关联汇总查询的问题就介绍到这里了,希望本次的介绍能够对您有所收获!