如何解决这个特定的SQL查询

时间:2015-03-30 10:33:51

标签: mysql sql-server-2008

我发布了3个这样的课程结构,这个课程,学生,CourseAllot with Data here我需要如何将多行组合成单行。如何显示基于名称连接并显示它们

Create Table Course 
( 
CourseId int Primary key Identity(1,1), 
CourseName Varchar(50) 
) 
Insert into Course values('C#') 
Insert into Course values('Asp.net') 
Insert into Course values('Sqlserver') 
Insert into Course values('MySql') 

Create Table Students 
( 
StudentId int Primary key identity(1,1), 
StudentName varchar(30) 
) 
Insert into Students values('John') 
Insert into Students values('David') 
Insert into Students values('Hendry') 
Insert into Students values('Smith') 
Insert into Students values('Watson') 



Create Table CourseAllot 
( 
AllotId int Primary key identity(1,1), 
CourseId int, 
StudentId int 
) 

Insert into CourseAllot values (1,1) 
Insert into CourseAllot values (1,1) 
Insert into CourseAllot values (2,1) 
Insert into CourseAllot values (1,2) 
Insert into CourseAllot values (3,4) 
Insert into CourseAllot values (3,5) 

我需要输出这个

Sno Course Name Student Name 
1   C#  John,Hendry,David 
2   Asp.net John 
3   Sqlserver   Smith,WatSon 

1 个答案:

答案 0 :(得分:0)

如果你在sqlserver中使用下面的查询

    with cte(courseName,c)
    as
    (select courseName,c= studentname from  CourseAllot 
    inner join Course on CourseAllot.CourseId=Course.CourseId 
    inner join Students on Students.StudentId=CourseAllot.StudentId  
    group by courseName,studentname
    ) 

    select ROW_NUMBER() over(order by courseName) as rowno, courseName,
    stuff((select ','+c from cte t where t.courseName=t2.courseName 
for xml path('')),1,1,'') as StudentName  from cte t2 group by t2.courseName