1、表结构

学生表Student(学号Sno、Sname姓名、Ssex性别、Sage年龄、所在系Sdept)

课程表Course(Cno课程号、Cname课程名、Cpon先行课、Ccredit学分)

选课表SC(学号Sno、Cno课程号、Grade分数)

SQL学生课程列拼接

2、查询

 

  
   select *  from Student a
   
   select *  from   Course  b  
   select *  from   SC  c 

 
 ----查询每个学生的平均分、课程数     
 select  a.Sno ,avg(c.Grade)as 'score',COUNT(c.Cno)as 'kcnum' from  dbo.Student a
  join  
  dbo.SC c on  a.Sno=c.Sno
  group  by a.Sno
  
  
  ---查询平均分大于70的学生、课程数
   select  a.Sno ,avg(c.Grade)as 'score',COUNT(c.Cno)as 'kcnum' from  dbo.Student a
  join  
  dbo.SC c on  a.Sno=c.Sno
  group  by a.Sno
  having avg(c.Grade)>70
  
  ---查询没有学课的学生(not  in和not   EXISTS两种写法 )
  select * from   Student a where  Sno  not         in  (select Sno   from SC c   )
  
   select * from   Student a where     not         EXISTS   (select Sno   from SC c   
    where a.Sno=c.Sno 
  )
  
  -----查询上了信息系统的学生
  
  select a.Sno,a.Sname,c.Cno,b.Cname,c.Grade  from  Student a
  join  SC c  on a.Sno=c.Sno
  join Course  b  on c.Cno=b.Cno
  where b.Cname ='信息系统'
  
  
   -----查询没有上信息系统的学生
  select a.Sname,a.Sno  from Student a where  a.Sno not  in (
  select Sno  from SC  c   where c.Cno=(select  Cno from Course  where Cname='信息系统')
  )
    
  select  a.Sno,MAX(a.Sname)as Name
     from Student a 
   where not  EXISTS(
  select Sno  from SC      where  Cno=(select  Cno from Course  where Cname='信息系统')
   and a.Sno=Sno 
   )
  group  by a.Sno
    
    
  -------   
    
 
 
  ---根据学号分组,拼接每一个学生的课程号
 select b.Sno, Cno=stuff((select ',' + Cno from SC as a where a.Sno = b.Sno for xml path('')),1 ,1,'')
from SC as b
group by b.Sno
 


 ----根据学号分组,拼接这个学生的课程名称
 select STUFF(( select ','+Cname    from   Course   b  
 where b.Cno   in(select Cno  from SC where  Sno='20190001')
 for  xml  path('')),1,1,'')
 
 
 
----根据学号分组,拼接当前学号下的学生的课程名称
 select b.Sno, Cname=stuff((select ',' + Cname from Course as a where a.Cno in(
  select  Cno  from  SC   where  Sno in(select Sno from SC  where SC.Sno=b.Sno)
 ) for xml path('')),1 ,1,'')
from SC as b
group by b.Sno
 
 


  

 

 

相关文章: