我需要查询我的要求。我有一个名为subject_details的表,它有2个字段。
student_Id std_subject
10 physics
20 physics
30 English
10 Maths
20 chemistry
我想返回以下记录:
student_id std_subject
10 physics,maths
20 physics,chemistry
30 English
答案 0 :(得分:0)
对于mysql,您可以使用group_concat
select student_id, group_concat(std_subject)
from subject_detials
group by student_id
答案 1 :(得分:0)
你可以在mysql中使用group_concat。 https://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat 试试这个:
select student_id as student_id, group_concat(std_subject) as std_subject
from subject_detials
group by student_id
答案 2 :(得分:0)
Oracle解决方案: 演示 @ ORACLE Fiddle
示例1 :
SELECT
"student_Id",
RTRIM( XMLAGG( XMLELEMENT( R, "std_subject", ',' )
.EXTRACT( '//text()' ) ),
',' ) subjects
FROM student_subjects
GROUP BY "student_Id";
结果1 :
+------------+-------------------+
| student_id | subjects |
+------------+-------------------+
| 10 | physics,Maths |
| 20 | physics,chemistry |
| 30 | English |
+------------+-------------------+
示例2 :
SELECT
"student_Id",
RTRIM( LISTAGG( "std_subject" || ',' )
WITHIN GROUP( ORDER BY 1 ),
',' ) subjects
FROM student_subjects
GROUP BY "student_Id";
结果2 :
+------------+-------------------+
| student_id | subjects |
+------------+-------------------+
| 10 | Maths,physics |
| 20 | chemistry,physics |
| 30 | English |
+------------+-------------------+
答案 3 :(得分:0)
使用LISTAGG功能(LISTAGG ORACLE DOC) 这将做你想要的。
SELECT
student_Id
,LISTAGG(std_subject, ',') WITHIN GROUP (ORDER BY std_subject) std_subject
FROM
student_subjects
GROUP BY
student_Id;