Mysql 如何解决这个特定的SQL查询
我已经发布了3个表结构,如本课程、学生、课程以及这里的很多数据。我需要如何将多行合并为一行。如何基于名称显示连接并显示它们Mysql 如何解决这个特定的SQL查询,mysql,sql-server-2008,Mysql,Sql Server 2008,我已经发布了3个表结构,如本课程、学生、课程以及这里的很多数据。我需要如何将多行合并为一行。如何基于名称显示连接并显示它们 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
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
如果您在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
你开始用SQL写东西了吗?您所要做的就是选择StudentName和CourseName,并使用GroupBy(CourseId)连接表。您面临的问题是哪一部分?您使用什么技术访问数据库?实体框架?是MySql还是SQL Server?基于您的标记,它的两个。。。