2015-03-30 3 views
-1

У меня есть сообщение 3 Структура таблиц, как этот курс, Студенты, CourseAllot с данными здесь Мне нужно, чтобы несколько строк объединяли одну строку. Как показать на основе имени concatenate и показать ихКак решить этот конкретный запрос SQL

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 
+2

вы начинаете ed пишет что-то в SQL? Все, что вам нужно сделать, - выбрать «StudentName» и «CourseName» с помощью GroupBy (CourseId) с присоединением таблиц. С какой частью вы столкнулись с проблемой? – SBirthare

+1

Какие технологии вы используете для доступа к базе данных? структура сущностей? –

+3

Является ли это MySql или SQL Server ?, на основе ваших тегов его оба ... –

ответ

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 
Смежные вопросы