我有针对学生的下表:
+----------+-------+-----+
|StudentID |Subject|Score|
+----------+-------+-----+
|1011010 |Phy |54 |
+----------+-------+-----+
|1011020 |Phy |78 |
+----------+-------+-----+
|1011010 |Maths |76 |
+----------+-------+-----+
|1011030 |Maths |65 |
+----------+-------+-----+
如何将结果显示为针对每个学生的单个连接字符串? 因此,在上面的数据中我应该返回以下内容:
+---------+---------------+
|StudentID|Result |
+---------+---------------+
|1011010 |Phy-54,Maths-76|
+---------+---------------+
|1011020 |Phy-78,Maths-65|
+---------+---------------+
我正在使用Sql server 2008。
答案 0 :(得分:2)
试试这个
SELECT StudentID,
( SELECT Subject + '-' + Score + ','
FROM students t2
WHERE t2.StudentID = t1.StudentID
ORDER BY Name
FOR XML PATH('') ) AS Name
FROM students t1
GROUP BY StudentID ;
答案 1 :(得分:-1)
Stuff()
应该这样做:
select t1.StudentID,
STUFF(
(SELECT ', ' + t2.Subject+ '-' + cast([Score] as varchar)
FROM Students t2
where t1.StudentID = t2.StudentID
FOR XML PATH (''))
, 1, 1, '') AS Grades
from Students t1
group by studentID