使用SQL Server在单元格中组合数据

时间:2015-08-14 20:22:34

标签: sql sql-server

我有一张桌子:

Student| Grade
qwe    | 100
qwe    | 95
qwe    | 90
asd    | 85
asd    | 90
zxc    | 80
zxc    | 75
zxc    | 100

和我的预期输出一样,我该怎么做?

Student | Grade
qwe     | 100; 95; 90
asd     | 85; 90
zxc     | 80; 75; 100

我试过这样但是错了:

SELECT d.Student, d.Grade FROM Data d GROUP BY d.Student

请帮助。

感谢大家。我使用了这个查询并且有效:

SELECT DISTINCT t1.Student, 
( SELECT t2.Grade+'; ' 
  FROM Data t2 
  WHERE t2.Student = t1.Student 
  FOR XML PATH('') ) Concatenated
FROM Data t1

1 个答案:

答案 0 :(得分:0)

我从Jpw的链接中复制了这个:

SELECT STUFF(
             (SELECT ',' + Column_Name 
              FROM Table_Name as [InteriorQuery]
              FOR XML PATH (''))
             , 1, 1, '')
FROM TABLE_NAME as [ExteriorQuery]

在STUFF内部,放置一个where子句,例如

where [InteriorQuery].Student = ExteriorQuery.Student