Sql 按组连接
我有下表列出了各科目的学生:Sql 按组连接,sql,sql-server,group-by,concatenation,Sql,Sql Server,Group By,Concatenation,我有下表列出了各科目的学生: +----------+-------+-----+ |StudentID |Subject|Score| +----------+-------+-----+ |1011010 |Phy |54 | +----------+-------+-----+ |1011020 |Phy |78 | +----------+-------+-----+ |1011010 |Maths |76 | +----------+-------
+----------+-------+-----+
|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。试试这个
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 ;
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
您需要将查询部分
,1,1',)替换为分数,1,0',)作为分数,您会在做出假设之前对其进行测试吗???如果我按照你的方式格式化它,我将保留前面的逗号。这就是我故意跳过它的原因。另外,我想分享下面的例子:Link。我已经测试了它,然后给出了评论<代码>Dhaval
答案是正确的。