Там может быть какое-то другое лучшее решение.Но это обеспечит ожидаемый результат -
SELECT B.id,
SUM(T_weight) Total_Weight,
group_concat(concat('TOP 5 ',B.cater,' (',B.T,')') SEPARATOR ' ') Details
FROM
(
SELECT ID,cater,SUM(Weight) T_weight,group_concat(weight SEPARATOR '+') T
FROM
(
SELECT * FROM
(
SELECT id,cater, CASE WHEN @ID = ID THEN @ROW_NUMBER := @ROW_NUMBER + 1 ELSE @ROW_NUMBER := 1 END AS rn,weight,@id := id
FROM your_table,(SELECT @ROW_NUMBER := 1, @ID := ''
) r
WHERE cater = 'Cheese' ORDER BY id, weight DESC
)A WHERE rn < 6
UNION ALL
SELECT * FROM
(
SELECT id,cater, CASE WHEN @ID = ID THEN @ROW_NUMBER := @ROW_NUMBER + 1 ELSE @ROW_NUMBER := 1 END AS rn,weight,@id := id
FROM your_table,(SELECT @ROW_NUMBER := 1, @ID := ''
) r
WHERE cater = 'Bacon' ORDER BY id, weight DESC
)A WHERE rn < 6
UNION ALL
SELECT * FROM
(
SELECT id,cater, CASE WHEN @ID = ID THEN @ROW_NUMBER := @ROW_NUMBER + 1 ELSE @ROW_NUMBER := 1 END AS rn,weight,@id := id
FROM your_table,(SELECT @ROW_NUMBER := 1, @ID := ''
) r
WHERE cater = 'Cat3' ORDER BY id, weight DESC
)A WHERE rn < 6
UNION ALL
SELECT * FROM
(
SELECT id,cater, CASE WHEN @ID = ID THEN @ROW_NUMBER := @ROW_NUMBER + 1 ELSE @ROW_NUMBER := 1 END AS rn,weight,@id := id
FROM your_table,(SELECT @ROW_NUMBER := 1, @ID := ''
) r
WHERE cater = 'Cat4' ORDER BY id, weight DESC
)A WHERE rn < 6
UNION ALL
SELECT * FROM
(
SELECT id,cater, CASE WHEN @ID = ID THEN @ROW_NUMBER := @ROW_NUMBER + 1 ELSE @ROW_NUMBER := 1 END AS rn,weight,@id := id
FROM your_table,(SELECT @ROW_NUMBER := 1, @ID := ''
) r
WHERE cater = 'Cat5' ORDER BY id, weight DESC
)A WHERE rn < 6
UNION ALL
SELECT * FROM
(
SELECT id,cater, CASE WHEN @ID = ID THEN @ROW_NUMBER := @ROW_NUMBER + 1 ELSE @ROW_NUMBER := 1 END AS rn,weight,@id := id
FROM your_table,(SELECT @ROW_NUMBER := 1, @ID := ''
) r
WHERE cater = 'Cat6' ORDER BY id, weight DESC
)A WHERE rn < 6
)A
GROUP BY ID,Cater
)B
group by id
Выход -
1 191 TOP 5 Cheese (10+22+20+10+30) TOP 5 Cat3 (25+9+20+16+13) TOP 5 Bacon (10)
2 45 TOP 5 Cheese (5+5) TOP 5 Bacon (15+10+10)