SELECT
  X.CMSInvNo,
  X.DocumentNumber,
  X.DocumentNumber AS InvoiceNumber,
  X.DocumentDate,
  X.AccountCode,
  X.ExternalInvoiceID,
  X.AccountBookType,
  X.AccountBookID,
  X.InvoiceAmountExcl,
  X.InvoiceAmountIncl,
  COALESCE(X.AmountCredited, 0.0) AS AmountCredited,
  (X.InvoiceAmountIncl - COALESCE(X.AmountCredited, 0.0)) AS CreditNoteAmount,
  X.CreditNoteOptions
FROM (

  SELECT
    IH.CMSInvNo,
    IH.DocumentNumber,
    IH.DocumentDate,
    IH.AccountCode,
    IH.ExternalID AS ExternalInvoiceID,
    IH.AccountBookType,
    IH.AccountBookID,
    IH.InvoiceAmountExcl,
    IH.InvoiceAmountIncl,
    (SELECT SUM(CN.CreditNoteAmount) FROM taCreditNote AS CN WHERE (CN.InvoiceNumber = IH.DocumentNumber) AND (COALESCE(CN.CreditNoteNumber, '') <> 'VOID')) AS AmountCredited,
    (SELECT OptionValue FROM taSystemOption WHERE (OptionType = 'CREDIT-NOTE-ACCOUNT') AND (OptionID = @nCreditNoteAccountID)) AS CreditNoteOptions
  FROM
    taInvoiceHeader AS IH
  WHERE
    (IH.CMSInvNo = @nCMSInvNo)

) AS X
