有关多表联合查询,解决了给分.
第一个表tblSales有:
usrID,grpID,SellDate,Sales(支出);
第二个表Fee有:
usrID,grpID,FeeDate,FeeMoney(收入)
如何查询出在指定时间段内总的FeeMoney和Sales
sql= "Select YEAR(FeeDate) AS feedate,grpName,Fee.grpID,COUNT(distinct Fee.usrID) AS renshu,SUM(FeeMoney) AS totalFee,SUM(Sales) AS totalSales FROM Fee,tblGroup,tblSales "
sql=sql & "where Fee.grpID=tblGroup.grpID "
sql=sql& " GROUP BY grpName,Fee.grpID,YEAR(FeeDate) order by feedate desc "
这样求出的是总的Sales,怎么加条件让它求出SellDate等于feedate的总的Sales.
年 用户组 部门人数 支出总额 收入总额
2006 销售三部 1 12000
2006 销售一部 2 66000
------解决方案--------------------select distinct AA.dt,AA.grpid,
(SELECT ISNULL(SUM(Sales),0) FROM tblSales WHERE Year(SellDate) = AA.dt AND grpid = AA.grpid) AS Sales
,
(SELECT ISNULL(SUM(FeeMoney),0) FROM Fee WHERE Year(FeeDate) = AA.dt AND grpid = AA.grpid) AS FeeMoney
FROM(
select Year(SellDate) dt ,grpid FROM tblSales
UNION ALL Select Year(FeeDate) dt,grpid FROM Fee) AS AA
------解决方案--------------------用视图建个虚拟表,把这几个表连合起来到时候就直接像操作一个表那样做就行了。非常方便。