我在SQL Server 2005中有像Rep_table,Selling,Upgrade和Delivery这样的表。
我正在尝试获得销售,升级和交付中的列数总和。 Rep_Table具有Rep_TableID,CommID和MerchantID列。 销售有SellingID,Rep_TableID,AmountSold,S_AmountCollected, 升级包含UpgradingID,Rep_TableID,AmountUpgraded,U_AmountCollected列 交货有列DeliveryID,Rep_TableID,D_AmountCollected
Rep_Table将有3条记录,每条记录用于销售,升级和交付。我的目标是获得已售出和升级的总和,从3张桌子和余额中收集的所有金额。
当我尝试以下查询时,我不会看到联接运作良好。此查询为我提供了1行销售,1行升级信息和每个商家的另一行交付。我正在寻找的是所有的计算都应该完成,每个商家都要排成一列。我希望我清楚地知道我在问什么。谢谢大家!
Select *, isnull(cast(S.AmountSold as numeric(10,2)), 0) + isnull(cast(U.AmountUpgraded as numeric(10,2)), 0) as AmountSold,
isnull(cast(S.S_AmountCollected as numeric(10,2)), 0) + isnull(cast(U.U_AmountCollected as numeric(10,2)), 0) + isnull(cast(D.D_AmountCollected as numeric(10,2)), 0) as AmountCollected,
(isnull(cast(S.AmountSold as numeric(10,2)), 0) + isnull(cast(U.AmountUpgraded as numeric(10,2)), 0)) -
(isnull(cast(S.S_AmountCollected as numeric(10,2)), 0) + isnull(cast(U.U_AmountCollected as numeric(10,2)), 0) + + isnull(cast(D.D_AmountCollected as numeric(10,2)), 0) ) as Balance
from Rep_Table RD
inner join Merchant M on M.MerchantID = RD.MerchantID --for MerchantInfo
left outer join SellingInfo S on S.RepInfoID = RD.RepInfoID
left outer join UpgradingInfo U on U.RepInfoID = RD.RepInfoID
left outer join DeliveryInfo D on D.RepInfoID = RD.RepInfoID
where RD.CommuniTeeID = @CommuniTeeID
答案 0 :(得分:0)
好的,给下面一个镜头:
Select sum(isnull(cast(S.AmountSold as numeric(10,2)), 0) + isnull(cast(U.AmountUpgraded as numeric(10,2)), 0)) as AmountSold
, sum(isnull(cast(S.S_AmountCollected as numeric(10,2)), 0) + isnull(cast(U.U_AmountCollected as numeric(10,2)), 0) + isnull(cast(D.D_AmountCollected as numeric(10,2)), 0)) as AmountCollected
, sum((isnull(cast(S.AmountSold as numeric(10,2)), 0) + isnull(cast(U.AmountUpgraded as numeric(10,2)), 0)) - (isnull(cast(S.S_AmountCollected as numeric(10,2)), 0) + isnull(cast(U.U_AmountCollected as numeric(10,2)), 0) + + isnull(cast(D.D_AmountCollected as numeric(10,2)), 0) )) as Balance
from Rep_Table RD
inner join Merchant M on M.MerchantID = RD.MerchantID --for MerchantInfo
left outer join SellingInfo S on S.RepInfoID = RD.RepInfoID
left outer join UpgradingInfo U on U.RepInfoID = RD.RepInfoID
left outer join DeliveryInfo D on D.RepInfoID = RD.RepInfoID
where RD.CommuniTeeID = @CommuniTeeID
group by m.MerchantID
我在每个列中添加了SUM
(我删除了*
,因为它可能使事情变得复杂)我在GROUP BY
上添加了m.MerchantID
。