SELECT
ISUM.id, FB, factIntiqol, (FB + factIntiqol) AS totalFact, PlanBd, PlanIntiqol, (PlanBd + PlanIntiqol) as TotalPlan
FROM (
Select
o.id,
Sum(fb.TransferSumm) 'FB'
from dbo.Offices o
Left join #FactBP fb
on fb.OfficeID =
o.ID group by
o.ID) FBSUM
JOIN (
Select
o.id,
Sum(i.CreditSumV) 'factIntiqol'
from dbo.Offices o
LEFT join #factIntiqol i on
o.ID = i.OfficeID
group by
o.ID) ISUM
ON
FBSUM.id =
ISUM.id JOIN (
Select
o.id,
isnull(max(OP.otp_bp_plan) + max(OP.vbp_plan),0) 'PlanBd'
from dbo.Offices o
LEFT join arvand.mtt_plan OP on
o.ID = OP.OfficeID
Where OP.PlanDate =
@maxPlanDate group by
o.ID) PBd
ON
FBSUM.id =
PBd.idJOIN (
Select
o.id,
isnull(max(OP.otp_intiqol_plan) + max(OP.vintiqol_plan),0) 'PlanIntiqol'
from dbo.Offices o
LEFT join arvand.mtt_plan OP on
o.ID = OP.OfficeID
Where OP.PlanDate =
@maxPlanDate group by
o.ID) PIntiqol
ON
FBSUM.id =
PIntiqol.id