SELECT * FROM (

    SELECT
      CP.ClientID,
      CS.FinNumber,
      CS.GroupName,
      PR.ProductName,
      PR.IsGrowthApplicable,
      CB.BranchName,
      PF.StartDate,
      C.RetainerFee AS PreviousRetainer,
      PF.RetainerFee AS NewRetainer,
      IF(C.RetainerFee IS NULL, PF.RetainerFee, (PF.RetainerFee - C.RetainerFee)) AS ActualGrowth,
      PF.Difference AS RecordedGrowth
    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)
    WHERE
      1
      @pFromTo

) AS Y
WHERE
  ((Y.IsGrowthApplicable > 0) AND (ROUND(Y.ActualGrowth, 2) <> ROUND(Y.RecordedGrowth, 2))) OR
  ((Y.IsGrowthApplicable = 0) AND (ROUND(Y.RecordedGrowth, 2) <> 0.0))
ORDER BY
  1,2,3,4,5,6
