SQL Server替代在聚合函数中使用子查询的方法

时间:2018-12-03 07:24:32

标签: sql sql-server group-by aggregate-functions

我正在使用汇总函数来计算特定学生的GPA。我有三个表: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)
);

我必须将ENROLL表中的char Grade转换为float值。在我的情况下,计算GPA的方法是:

SUM(grade of each course*credit hours of the course)/SUM(credit hours of each course)

这是我当前尝试计算GPA的方式:

 @grade =     
(
 (select SUM(CASE 
              WHEN Grade = 'A' THEN 4.0
              WHEN Grade = 'B' THEN 3.0
              WHEN Grade = 'C' THEN 2.0
              WHEN Grade = 'D' THEN 1.0
              WHEN Grade = 'F' THEN 0.0
             END
             * (
                select c.Credit from COURSE c where c.Cno = (
                 select s.Cno from SECTION s where s.Sid in (
                  select Sid from ENROLL where Mno = @mNum
                 )
                )
             )
         ) FROM ENROLL 
         where Mno = @mNum 
 ) / (
  select SUM(Credit) from COURSE c where c.Cno = (
   select s.Cno from SECTION s where s.Sid in (
    select Sid from ENROLL where Mno = @mNum
   )
  ) group by c.Cno
 )
)

但是,有一个明显的问题。您不能在聚合函数中包含子查询,因此我一直难以找到替代方法。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:4)

似乎您只需要将三个表联接在一起即可:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {       
    if collectionView == filterCollectionView {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FilterSelectionCollectionViewCell", for: indexPath) as! FilterSelectionCollectionViewCell
        return CGSize(width: cell.title.frame.width , height: self.filterCollectionView.frame.height)
    }  else {
        return CGSize(width: 10, height: 10)
    }
}

答案 1 :(得分:2)

我要尝试的是先加入表注册和SECTION。

这将为我提供与Mno相关的所有部分。

之后,我将与COURSE表一起获取与Mno相关的所有课程。

选择*   从注册一个   加入b节     在a.Sid = b.Sid上   参加课程c     在b.Cno = c.Cno

然后我将按a.Mno分组。这意味着我正在根据定义的计算来计算每Mno的GPA。

**SUM(grade of each course*credit hours of the course)/SUM(credit hours of each course)**

select a.Mno
       ,sum(case WHEN c.Grade = 'A' THEN 4.0
                 WHEN c.Grade = 'B' THEN 3.0
                 WHEN c.Grade = 'C' THEN 2.0
                 WHEN c.Grade = 'D' THEN 1.0
                 WHEN c.Grade = 'F' THEN 0.0
             END * c.Credit)/sum(c.credit) 
  from enroll a
  join section b
    on a.Sid=b.Sid
  join course c
    on b.Cno=c.Cno
group by a.Mno