INSERT IGNORE INTO taClientRetentionSummary (
  YearMonth,
  ClientID,
  LabourNetBranchID,
  ConsultantID,
  SalesCloserID,
  ProductID,
  IsHeadOffice,
  FinNumber,
  Retainer
)

SELECT DISTINCT
  @nYearMonth AS YearMonth,
  CP.ClientID,
  CB.LabourNetBranchID,
  BP.ConsultantID,
  BP.SalesCloserID,
  CP.ProductID,
  CB.IsHeadOffice,
  CS.FinNumber,
  fnClientBranchProductRetainer(BP.ClientBranchProductID, @aMonthEnd) AS Retainer
FROM
  taClientBranchProducts AS BP
    INNER JOIN taClientProducts AS CP ON (CP.ClientProductID = BP.ClientProductID)
    INNER JOIN taClientBranches AS CB ON (CB.ClientBranchID = BP.ClientBranchID)
    INNER JOIN taClients        AS CS ON (CS.ClientID = CP.ClientID)
    INNER JOIN taProducts       AS PR ON (PR.ProductID = CP.ProductID)
WHERE
  (BP.JoinDate <= @aMonthEnd) AND
  ((BP.TerminationDate IS NULL) OR (BP.TerminationDate > @aMonthEnd)) AND
  (fnClientBranchProductRetainer(BP.ClientBranchProductID, @aMonthEnd) > 0.0) AND
  (CB.LabourNetBranchID NOT IN (18,116)) AND
  (CP.ProductID <> 14)

ORDER BY 1,2,3,4,5,6,7
