连接,如何将列中的不同值合并为一行?

时间:2016-08-29 13:06:30

标签: sql-server

我正在尝试列出课程编号,然后在一行中显示课程涵盖的成绩。我尝试了连接,但它将它放在不同的行上。我想看看:

6740    , , , 10, 11, 12.

但我得到了这个:

courseID    Grades
6740    , , , , , 12
6740    , , , , 11, 
6740    , , , 10, , 

这是我使用的代码(成绩是字符串,而不是数字):

select distinct c.courseID
,case when st.grade = '7' then '7' else '' end 
+ ', '
+ case when st.grade = '8' then '8' else ''end 
+ ', '
+ case when st.grade = '9' then '9' else ''end
+ ', '
+ case when st.grade = '10' then '10' else ''end
+ ', '
+ case when st.grade = '11' then '11' else ''end
+ ', '
+ case when st.grade = '12' then '12' else '' end
as Grades
from course c
inner join calendar cal on cal.calendarID = c.calendarID

inner join Section s on s.courseID = c.courseID
inner join Trial tr on tr.trialID = s.trialID and tr.calendarID =        cal.calendarID
    and tr.active = 1
inner join Roster r on r.sectionID = s.sectionID
inner join student st on st.personID = r.personID and st.calendarID = cal.calendarID
inner join sectionPlacement sp on sp.sectionID = s.sectionID
where c.calendarID in (1058, 1054)
    and c.active = 1

有人可以帮助引导我朝着正确的方向前进,每门课程显示所有成绩吗?我使用的是Microsoft SQL 2012

1 个答案:

答案 0 :(得分:0)

也许是这样的:

简短说明:此方法模拟 MySQL-Group-Concat 。如果您需要专用列中的成绩,则需要PIVOTGROUP BY with MAX(CASE...)或动态SQL。

DECLARE @course TABLE(ID INT,CoursName VARCHAR(100));
INSERT INTO @course VALUES(6740,'Course 6740'),(9999,'Course 9999');

DECLARE @grade TABLE(ID INT,GradeName VARCHAR(100));
INSERT INTO @grade VALUES(7,'Grade 7'),(8,'Grade 8'),(9,'Grade 9');


DECLARE @data TABLE(CourseID INT, GradeID INT);
INSERT INTO @data 
VALUES
 (6740,7),(6740,8),(6740,9)
,(9999,7),(9999,9);

SELECT d.CourseID
      ,c.CoursName
      ,STUFF(
          (
            SELECT ', ' + g.GradeName
            FROM @data AS d1
            INNER JOIN @grade AS g ON d1.GradeID=g.ID
            WHERE d1.CourseID=d.CourseID
            FOR XML PATH('')
          ),1,2,'') AS Grades

FROM @data AS d
INNER JOIN @course AS c ON d.CourseID=c.ID
GROUP BY  d.CourseID,c.CoursName

这是结果

CourseID    CoursName     Grades
6740        Course 6740   Grade 7, Grade 8, Grade 9
9999        Course 9999   Grade 7, Grade 9