SELECT
  AJ.AccountBookType,
  AJ.AccountBookID,
  XE.ShortCode,
  XE.XeroEntityName AS AccountBookName,
  AJ.JournalDate,
  AJ.JournalNumber,
  AJ.Reference,
  AJ.SourceType,
  AJ.SourceExternalID,
  JL.AccountCode,
  JL.AccountName,
  JL.AccountType,
  JL.LineNumber,
  JL.Description,
  JL.BranchRegion,
  JL.ProductCategory,
  IF(JL.NetAmount >= 0.0, 1.0 * JL.NetAmount, 0.0) AS Debit,
  IF(JL.NetAmount < 0.0, -1.0 * JL.NetAmount, 0.0) AS Credit,
  JL.GrossAmount,
  JL.TaxAmount
FROM
  taAccountBookJournal AS AJ
    LEFT JOIN taAccountBookJournalLine AS JL ON ((JL.AccountBookType = AJ.AccountBookType) AND (JL.AccountBookID = AJ.AccountBookID) AND (JL.JournalNumber = AJ.JournalNumber))
    LEFT JOIN taXeroEntity             AS XE ON (XE.XeroEntityID = AJ.AccountBookID)
WHERE
  (AJ.AccountBookType = 'Xero') AND
  ((@nAccountBookID = 0) OR (AJ.AccountBookID = @nAccountBookID)) AND
  (AJ.JournalDate >= @aFromDate) AND
  (AJ.JournalDate <= @aToDate) AND
  ((@aAccountCode = '') OR (JL.AccountCode = @aAccountCode))
ORDER BY
  AJ.JournalDate,
  AJ.JournalNumber,
  JL.LineNumber
