mysql查询获取与重复记录对应的数据

时间:2015-01-16 05:59:36

标签: mysql sql select group-by group-concat

这是一个表名test1

id  Roll Rank Grade
1    10   50   A
2    20   60   B
3    30   40   X
4    20   50   A
5    30   90   O
6    10   80   C

希望得到以下格式的结果:

id  Roll   Rank    Grade
1    10   50,80     A,C
2    20   60,80     B,A
3    30   40,90     X,O

2 个答案:

答案 0 :(得分:0)

这样可以解决问题:

SELECT id, Roll, GROUP_CONCAT(Rank), GROUP_CONCAT(Grade)
FROM your_table
GROUP BY Roll
HAVING COUNT(*) > 1

答案 1 :(得分:0)

试试这个:

SELECT A.id, A.Roll, 
       GROUP_CONCAT(A.Rank ORDER BY A.id) AS Rank, 
       GROUP_CONCAT(A.Grade ORDER BY A.id) AS Grade
FROM test1 A 
GROUP BY A.Roll
ORDER BY A.Roll;