SELECT
  X.StartDate,
  COALESCE((SELECT
    SUM(PF.RetainerFee)
  FROM
    taClientBranchProducts AS BP
      LEFT JOIN taClientProducts AS CP ON (CP.ClientProductID = BP.ClientProductID)
      LEFT JOIN taClientBranches AS CB ON (CB.ClientBranchID = BP.ClientBranchID),
    taClientProductFees AS PF
  WHERE
    (CP.ClientID = @nClientID)
    @pClientProductID
    @pClientBranchID
    AND (PF.ClientBranchProductID = BP.ClientBranchProductID)
    AND (PF.ClientProductFeeID = (

      SELECT MAX(M.ClientProductFeeID)
      FROM taClientProductFees AS M
      WHERE
        (M.ClientBranchProductID = BP.ClientBranchProductID) AND
        (M.StartDate = (

          SELECT MAX(N.StartDate)
          FROM taClientProductFees AS N
          WHERE
            (N.ClientBranchProductID = M.ClientBranchProductID) AND
            (N.StartDate <= X.StartDate)

        ))
    ))), 0.0) AS RetainerFee
FROM (

  SELECT DISTINCT
    PF.StartDate
  FROM
    taClientProductFees AS PF
      LEFT JOIN taClientBranchProducts AS BP ON (BP.ClientBranchProductID = PF.ClientBranchProductID)
      LEFT JOIN taClientProducts AS CP ON (CP.ClientProductID = BP.ClientProductID)
  WHERE
   (ClientID = @nClientID)
   @pClientProductID
   @pClientBranchID

) AS X
GROUP BY
  X.StartDate
ORDER BY
  X.StartDate
