declare @contractcoreid int
set @contractcoreid = 07125273
SELECT gla.AccountNumber, SUM(at.Amount) as 'Total Amount' ,
gla.Definition
FROM EffectiveTerm et
JOIN ContractCoverage cc
ON et.Id = cc.EffectiveTermId
JOIN AccountingTransactionGroup atg
ON cc.Id = atg.contractCoverageId
JOIN AccountingTransaction at
ON atg.Id = at.AccountingTransactionGroupId
JOIN GeneralLedgerAccount gla
ON at.GeneralLedgerAccountId = gla.Id
LEFT JOIN OrderLineReference ol
ON atg.OrderLineReferenceId = ol.Id
WHERE
--et.ContractId IN (SELECT Id FROM Contract WHERE ContractCoreId = 03111021)
cc.Id in (SELECT max(b.id) FROM EffectiveTerm a join ContractCoverage b on a.id = b.EffectiveTermId
join contract cl on cl.id = a.ContractId
WHERE cl.ContractCoreId = @contractcoreid and b.id <(SELECT max(b.id)
FROM EffectiveTerm a
join ContractCoverage b on a.id = b.EffectiveTermId
join contract cl on cl.id = a.ContractId
WHERE cl.ContractCoreId = @contractcoreid))
GROUP BY cc.Id, gla.AccountNumber, gla.Definition
Union
SELECT
AccountNumber,null as 'Total Amount ', Definition
FROM [dbo].[GeneralLedgerAccount] gl