SELECT
m.KH,
GROUP_CONCAT(CP) AS CPXH -- 可能会出现多个产品购买次数相同的情况,GROUP_CONCAT拼接产品;
FROM
(
SELECT
KH,
CP,
count(1) AS GMCS
FROM
tablename
GROUP BY
KH,
CP
) m
LEFT JOIN (
SELECT
KH,
max(GMCS) AS MAX_GMCS -- 每个客户最大的购买次数
FROM
(
SELECT
KH,
CP,
count(1) AS GMCS -- 每个客户分产品的购买次数
FROM
tablename
GROUP BY
KH,
CP
) a
GROUP BY
KH
) n ON m.KH = n.KH -- 客户关联
AND m.GMCS = n.MAX_GMCS -- 购买次数 = 最大购买次数
GROUP BY
m.KH