SELECT
  JL.CMSJournalNo,
  JL.CMSJournalLineNo,
  JL.CMSInvNo,
  JL.ItemNumber,
  JL.CMSLineNo,
  JL.Description,
  JL.DebitAccount,
  JL.DebitTaxType,
  JL.DebitBranchRegion,
  JL.DebitProductCategory,
  JL.CreditAccount,
  JL.CreditTaxType,
  JL.CreditBranchRegion,
  JL.CreditProductCategory,
  (JL.LineAmount - COALESCE(A.LineAmountCredited, 0.0)) AS LineAmount
FROM
  taManualJournalLine AS JL
    LEFT JOIN (

      SELECT
        LinkCMSInvNo AS CMSInvNo,
        LinkItemNumber AS ItemNumber,
        LinkCMSLineNo AS CMSLineNo,
        SUM(LineAmount) AS LineAmountCredited
      FROM
        taManualJournalLine AS JL
      WHERE
        (LinkCMSInvNo = @nCMSInvNo) AND
        (LinkItemNumber = @nItemNumber)
      GROUP BY
        1,2,3

    ) AS A ON ((A.CMSInvNo = JL.CMSInvNo) AND (A.ItemNumber = JL.ItemNumber) AND (A.CMSLineNo = JL.CMSLineNo))
WHERE
  (JL.CMSInvNo = @nCMSInvNo) AND
  (JL.ItemNumber = @nItemNumber)
ORDER BY
  1,2,3
