需要SQL内部子查询计算帮助

时间:2015-05-20 11:32:27

标签: join subquery correlated-subquery inner-query

我想从totalammount计算余额运行时间 - AmmountReceived =平衡下一行..

Totalammont(实际上将是以前的运行时计算余额应该在这里) - AmmountReceived = Balance等等....

这是我的查询,它不会减少totalAmmount

select ID,
       RecvDate,
       BillNo,
       ModeofPayment,
       (Select Item_name from Product where ID = CampusRecovery.ItemID) as Item,
       SUM(AmountReceived) as AmountReceived,
       (Select CampusName from Campus where CampusID = CampusRecovery.CampusID) as Campus,
       IsNull((select SUM(Inventory_Out.TotalAmount)
               from Inventory_Out
               where Inventory_Out.BillNo = CampusRecovery.BillNo),0) as TotalAmmount,
       IsNull((select SUM(Inventory_Out.TotalAmount)
               from Inventory_Out
               where Inventory_Out.BillNo = CampusRecovery.BillNo),0) - SUM(AmountReceived) as Balance
from CampusRecovery 
where RecvDate Between @startdt and @enddt
  and CampusID = 2
Group By CampusRecovery.CampusID,
         CampusRecovery.ItemID,
         CampusRecovery.RecvDate,
         CampusRecovery.BillNo,
         CampusRecovery.ModeofPayment,
         CampusRecovery.ID

enter image description here

1 个答案:

答案 0 :(得分:0)

select cr.BillNum, cr.DelievryDate,cr.AmmountReceived,(select TotalAmmount from InventoryOut where InventoryOut.BillNum = cr.BillNum) as TotalBill,
(select TotalAmmount -
(select Sum(AmmountReceived) from CampusRecovery ch where ch.BillNum = io.BillNum )
 from InventoryOut io where io.BillNum = cr.BillNum )--- sum(cr.AmmountReceived)
as Balance
from CampusRecovery  cr where CampusID = 1
group by 
cr.BillNum,
cr.DelievryDate,
cr.BillNum,
cr.AmmountReceived