SELECT
  BR.BranchID,
  IH.ClientID,
  CS.GroupName,
  CS.FinNumber,
  COALESCE(IF(IH.AccountBookType = 'Xero', XE.XeroEntityName, IF(IH.AccountBookType = 'Sage', SE.SageEntityName, NULL)), CONCAT(IH.AccountBookType, '_', IH.AccountBookID)) AS AccountBookName,
  IH.DocumentNumber,
  CASE IH.InvoiceType
    WHEN 'A' THEN 'Ad-Hoc'
    WHEN 'I' THEN 'Imported'
    ELSE CONCAT('Unknown [', IH.InvoiceType, ']')
  END AS InvoiceType,
  IH.DocumentDate,
  IL.Description,
  BR.BranchRegion,
  PC.ProductCategory,
  IL.GLAccount,
  IL.BranchRegion AS RegionTrackingCategory,
  IL.ProductCategory AS ProductTrackingCategory,
  IL.ExclusivePrice AS AdHocRevenue
FROM
  taInvoiceLine AS IL
    LEFT JOIN taInvoiceHeader   AS IH ON (IH.CMSInvNo = IL.CMSInvNo)
    LEFT JOIN taSageEntity      AS SE ON ((SE.SageEntityID = IH.AccountBookID) AND (IH.AccountBookType = 'Sage'))
    LEFT JOIN taXeroEntity      AS XE ON ((XE.XeroEntityID = IH.AccountBookID) AND (IH.AccountBookType = 'Xero'))
    LEFT JOIN taBranches        AS BR ON (BR.TrackingCategory = IL.BranchRegion)
    LEFT JOIN taProductCategory AS PC ON (PC.TrackingCategory = IL.ProductCategory)
    LEFT JOIN taClients         AS CS ON (CS.ClientID = IH.ClientID)
WHERE
  (IH.DocumentNumber IS NOT NULL) AND
  (IH.DocumentNumber <> 'VOID') AND
  (IH.InvoiceType IN ('A','I')) AND
  (IH.Updated = 1) AND
  (IL.ExclusivePrice > 0.0)
  @pAccountBook
  @pBranchRegion
  @pProductCategory
  @pFromTo
ORDER BY
  CS.GroupName
