0

我在 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 行中的升级信息和每个商家的另一行中的交付。我正在寻找的是所有计算都应该完成并且每个商家都在 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
4

1 回答 1

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 BYon m.MerchantID

于 2013-01-30T15:46:43.437 回答