使用Count Function SQL

时间:2013-04-03 19:11:43

标签: sql sql-server

好的我正在尝试使用此计数函数来计算case语句的不同部分。这是现在的工作代码。它会告诉我某人在学校开始的那一年。学年如何分解是200703年是07年夏季,200801年是07年秋季,200802年是08年春季。所以案例陈述给了我一个学生开始的学年。我只需要一个简单的方法来计算每学年有多少一年级学生。我尝试在case语句周围使用Count并尝试设置不同的方法来计算它但总是遇到聚合函数错误。任何帮助都会很棒。我在SQL Server 2008 R2中写这个

SELECT DISTINCT dbo.student_crs_hist.id_num,   
     sum(dbo.student_crs_hist.credit_hrs) as 'tot_credit_hrs',   
     min(dbo.student_crs_hist.yr_cde+dbo.STUDENT_CRS_HIST.TRM_CDE)  as 'first_year',
     'Year' = CASE
     WHEN min(dbo.student_crs_hist.yr_cde+dbo.STUDENT_CRS_HIST.TRM_CDE)in ('200703','200801','200802') Then '20007-2008'
     WHEN min(dbo.student_crs_hist.yr_cde+dbo.STUDENT_CRS_HIST.TRM_CDE)in ('200803','200901','200902') Then '20008-2009'
     WHEN min(dbo.student_crs_hist.yr_cde+dbo.STUDENT_CRS_HIST.TRM_CDE)in ('200903','201001','201002') Then '20009-2010'
     WHEN min(dbo.student_crs_hist.yr_cde+dbo.STUDENT_CRS_HIST.TRM_CDE)in ('201003','201101','201102') Then '2010-2011'
     Else '2011-2012'
     END
FROM dbo.student_crs_hist,   
     dbo.degree_history 
WHERE dbo.student_crs_hist.id_num = dbo.degree_history.id_num  and  
        ((dbo.STUDENT_CRS_HIST.YR_CDE in ('2007') and dbo.STUDENT_CRS_HIST.TRM_CDE in ('03')) OR 
       (dbo.student_crs_hist.yr_cde in ( '2008','2009','2010','2011')  AND  dbo.student_crs_hist.trm_cde in ( '01','02','03' ))OR
         (dbo.STUDENT_CRS_HIST.YR_CDE in ('2012') and dbo.STUDENT_CRS_HIST.TRM_CDE in ('01','02'))) and 
      dbo.student_crs_hist.transaction_sts in ( 'C','H' )  AND  
      dbo.student_crs_hist.grade_cde in ( 'A','B','C' )  AND  
      dbo.degree_history.major_1 = 'ASBD' and
      dbo.student_crs_hist.adv_req_cde not in ('COL081','EGL082','EGL092','EGL093','MAT091','MAT092','MAT093','COM091','EGL100','REA100')  
Group By
     dbo.STUDENT_CRS_HIST.ID_NUM 
Having
     sum(dbo.student_crs_hist.credit_hrs) >= '30' and

     (min(dbo.student_crs_hist.yr_cde+dbo.STUDENT_CRS_HIST.TRM_CDE) = '200703' or
     min(dbo.student_crs_hist.yr_cde) in ('2008','2009','2010','2011') or
     MIN(dbo.student_crs_hist.yr_cde+dbo.student_crs_hist.trm_cde) in ('201201','201202'))
    Order By
    min(dbo.student_crs_hist.yr_cde+dbo.STUDENT_CRS_HIST.TRM_CDE)

1 个答案:

答案 0 :(得分:0)

尝试这种方法:

...
SUM(
   CASE WHEN min(dbo.student_crs_hist.yr_cde+dbo.STUDENT_CRS_HIST.TRM_CDE)in ('200703','200801','200802') Then 1 ELSE 0 END
   ) as FirstYearStudents_07-08
...