Problem
How to make query Substract AmountDue For Invoice from Customer Balance .
Balance Customer query :
SELECT VTargetDetail.BranchCode ,VTargetDetail.SubLdgCode as UnitCode ,(SUM(dbo.VTargetDetail.Debit * dbo.VTargetDetail.CurrencyRate) - SUM(dbo.VTargetDetail.Credit * dbo.VTargetDetail.CurrencyRate) ) as Balance
FROM dbo.VTargetDetail LEFT OUTER JOIN
dbo.TypeTrxSafe ON dbo.VTargetDetail.BranchCode = dbo.TypeTrxSafe.BranchCode AND dbo.VTargetDetail.TrxTypeCode = dbo.TypeTrxSafe.SafeTrxTypeCode WHERE (1 = 1) AND (VTargetDetail.TrxDate <= '2018/09/17') AND (VTargetDetail.SubLdgCodeType = 28) AND (VTargetDetail.SubLdgCode=5639) group by VTargetDetail.SubLdgCode,VTargetDetail.BranchCode
AmountDue For Invoice query as following :
select BranchCode,UnitCode,RequiredAmount, Serial,Year,Month,CurrentReadingDate,CurrentMeterReading,LastMeterReading,CurrentConsumption,CurrentConsumptionValue ,VATValue,CleaningFees from WAHInvoice where 1=1 AND year=2018 AND BranchCode = 1 and Month=5 and UnitCode=5639
How to substract Balance from First Query represent Balance Customer query
From
RequiredAmount on second Query AmountDue For Invoice query
Meaning Balance - RequiredAmount
and I need result display on one query .
this query above must return one record meaning final result one record
BranchCode UnitCode Difference
1 5639 CustomerBalance - requiredamount
How To Do That by union
What I have tried:
select BranchCode,UnitCode,RequiredAmount, Serial,Year,Month,CurrentReadingDate,CurrentMeterReading,LastMeterReading,CurrentConsumption,CurrentConsumptionValue ,VATValue,CleaningFees
from
(
select BranchCode,UnitCode,RequiredAmount, Serial,Year,Month,CurrentReadingDate,CurrentMeterReading,LastMeterReading,CurrentConsumption,CurrentConsumptionValue ,VATValue,CleaningFees from WAHInvoice where 1=1 AND year=2018 AND BranchCode = 1 and Month=5 and UnitCode=5639
union
SELECT VTargetDetail.BranchCode ,VTargetDetail.SubLdgCode as UnitCode ,(SUM(dbo.VTargetDetail.Debit * dbo.VTargetDetail.CurrencyRate) - SUM(dbo.VTargetDetail.Credit * dbo.VTargetDetail.CurrencyRate) ) as Balance,'' AS Serial,'' as YEAR,'' AS Month,'' as CurrentReadingDate,'' as CurrentMeterReading,'' as LastMeterReading,'' as CurrentConsumption,'' as CurrentConsumptionValue,'' as VATValue,'' as CleaningFees
FROM dbo.VTargetDetail LEFT OUTER JOIN
dbo.TypeTrxSafe ON dbo.VTargetDetail.BranchCode = dbo.TypeTrxSafe.BranchCode AND dbo.VTargetDetail.TrxTypeCode = dbo.TypeTrxSafe.SafeTrxTypeCode WHERE (1 = 1) AND (VTargetDetail.TrxDate <= '2018/09/17') AND (VTargetDetail.SubLdgCodeType = 28) AND (VTargetDetail.SubLdgCode = 5639) group by VTargetDetail.SubLdgCode,VTargetDetail.BranchCode
)as INV
I face more problem
Error converting data type varchar to numeric.
also how to get substract balance field from second query - reuired amount from first query