SELECT * FROM (

  SELECT
    CP.ClientID,
    CS.FinNumber,
    CS.GroupName,
    PF.StartDate,
    BR.TrackingCategory AS Region,
    PC.TrackingCategory AS Product,
    SUM(IF(PF.EntryType IN ('N'), IF(C.RetainerFee IS NULL, PF.RetainerFee, (PF.RetainerFee - C.RetainerFee)), 0.0)) AS NewSales,
    SUM(IF((PF.EntryType IN ('M')) AND (PF.RetainerFee > C.RetainerFee), IF(C.RetainerFee IS NULL, PF.RetainerFee, (PF.RetainerFee - C.RetainerFee)), 0.0)) AS ExistingSales,
    'RT' AS RevenueType,
    PC.ProductCategory,
    GROUP_CONCAT(PR.ProductName) AS ProductName,
    U1.FullName AS SalesPerson,
    U1.EmployeeCode AS SalesPersonEmployeeCode,
    U2.FullName AS SalesReferrer,
    U2.EmployeeCode AS SalesReferrerEmployeeCode
  FROM
    taClientProductFees AS PF
      LEFT JOIN (

        SELECT
          A.ClientProductFeeID,
          ( SELECT MAX(M.ClientProductFeeID)
            FROM taClientProductFees AS M
            WHERE
              (M.ClientBranchProductID = A.ClientBranchProductID) AND
              (M.ClientProductFeeID <> A.ClientProductFeeID) AND
              (M.StartDate = (

                SELECT MAX(N.StartDate)
                FROM taClientProductFees AS N
                WHERE
                  (N.ClientBranchProductID = A.ClientBranchProductID) AND
                  (
                    (N.StartDate < A.StartDate) OR
                    ((N.StartDate = A.StartDate) AND (N.ClientProductFeeID < A.ClientProductFeeID))
                  )

              ))
          ) AS PreviousID
        FROM
          taClientProductFees AS A

      ) AS X USING (ClientProductFeeID)
      LEFT JOIN taClientProductFees AS C ON (C.ClientProductFeeID = X.PreviousID)
      LEFT JOIN taClientBranchProducts AS BP ON (BP.ClientBranchProductID = PF.ClientBranchProductID)
      LEFT JOIN taClientProducts AS CP ON (CP.ClientProductID = BP.ClientProductID)
      LEFT JOIN taClientBranches AS CB ON (CB.ClientBranchID = BP.ClientBranchID)
      LEFT JOIN taClients AS CS ON (CS.ClientID = CP.ClientID)
      LEFT JOIN taProducts AS PR ON (PR.ProductID = CP.ProductID)
      LEFT JOIN taProductCategory AS PC ON (PC.ProductCategory = PR.ProductCategory)
      LEFT JOIN taBranches AS BR ON (BR.BranchID = CB.LabourNetBranchID)
      LEFT JOIN taUsers AS U1 ON (U1.UserID = BP.SalesCloserID)
      LEFT JOIN taUsers AS U2 ON (U2.UserID = BP.SalesReferrerID)
  WHERE
    (PF.EntryType IN ('N','C','S','M'))
    @pFromTo
  GROUP BY
    1,2,3,4,5,6,9,10,12,13,14,15

) AS X
WHERE
  ((X.NewSales + X.ExistingSales) > 0.0)
