SQL sum聚合函数存在问题

时间:2018-12-03 05:24:38

标签: sql sum aggregate-functions

我正在尝试对具有3个表的数据库进行查询:COURSE,SECTION,ENROLL。

他们正在这样创建:

create table COURSE
(
    Cno     varchar(9) primary key, 
    Cname   varchar(50),
    Credit  int check (Credit > 0)
);

create table SECTION
(
    Cno     varchar(9) REFERENCES COURSE(cno),
    Sno     varchar(9),
    Semester    varchar(15) check(Semester in('Fall','Spring','Summer')), 
    Year    int, 
    Sid     varchar(9) primary key 
);

create table ENROLL
(
    Mno     varchar(9) REFERENCES STUDENT(Mno),
    Sid     varchar(9) REFERENCES SECTION(Sid),
    Grade   CHAR check(Grade in('A','B','C','D','F')),
    primary key(Mno,Sid)
);

我正在尝试对学生所注册课程的所有学分运行SUM。这就是我试图达到的目的:

select 
    SUM(select Credit 
        from COURSE c 
        where c.Cno = (select s.Cno 
                       from SECTION s 
                       where s.Sid = (select Sid 
                                      from ENROLL 
                                      where Mno = @mNum));

但是我在Visual Studio中遇到一条错误消息

  

“ select”(第二个select语句)附近的语法不正确

这是什么问题?任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:1)

查看是否有效

select sum(Credit) from COURSE c where c.Cno in 
(select s.Cno from SECTION s where s.Sid in (select Sid from ENROLL where Mno = @mNum)) 
group by c.Cno;

答案 1 :(得分:1)

尝试一下:

select SUM((select Credit from COURSE c where c.Cno = 
(select s.Cno from SECTION s where s.Sid = (select Sid from ENROLL where Mno = @mNum)));

答案 2 :(得分:1)

例如,如果Mno可以注册多个部分,则需要输入IN而不是=

select sum(Credit) 
   from COURSE c 
  where c.Cno in (select s.Cno 
                    from SECTION s 
                   where s.Sid in (select Sid 
                                    from ENROLL where Mno = @mNum)
                  )