从MySQL中的2个表中执行SELECT COUNT

时间:2014-11-21 16:39:19

标签: mysql sql

我有两张桌子学生和课程。

STUDENT有以下专栏:

SID INTERGER
NAME VARCHAR
DEPARTMENT INTEGER
REGISTRATIONDATE DATE

COURSE有以下几栏:

CID INTERGER
SID INTERGER
ENROLLEDATE 

我想获得每个注册日期的学生总数,按部门和每个课程注册的学生数量,该注册日期可以通过注册日期和注册日期之间的注册来确定

如果我的输入数据是:

STUDENT:
1,John,CS,11/01/2014
2,Jim,CS,11/01/2014
3,Jane,LAW,10/01/2014
4,Rose,Engineering,11/01/2014

COURSE:
1,1,11/10/2014
1,2,11/11/2014
2,3,11/11/2014

OUTPUT:
StudentCount,Department,RegistrationDate,StudentInCourseCount
2,CS,11/01/2014,2
1,LAW,10/01/2014,1
1,Engineering,11/01/2014,

StudentCount =在每个注册日期注册部门的学生人数

部门=该计数的部门名称

RegistrationDate =每个唯一注册期

StudentInCourseCount =注册日期与注册日期+ 28之间注册的每门课程的学生人数

注意:OUTPUT中最后一行的StudentInCourseCount为空,因为Rose未在任何课程中注册。

试图尽可能清楚地解释它。

这是我的尝试,但StudentInCourseCount没有正确出现,

SELECT COUNT(sd.SID) As STUDENTCOUNT,sd.DEPARTMENT,sd.REGISTRATIONDATE,
(
    SELECT COUNT(p.SID) 
    FROM COURSE p
    WHERE sd.SID=p.SID AND p.ENROLLDATE BETWEEN sd.REGISTRATIONDATE AND sd.REGISTRATIONDATE+28 
 )  AS StudentInCourseCount
FROM STUDENT sd
GROUP BY DEPARTMENT,REGISTRATIONDATE
ORDER BY REGISTRATIONDATE DESC;

感谢。

2 个答案:

答案 0 :(得分:1)

试试这个。使用Conditional Aggregate逻辑查找StudentInCourseCount。更新:Osa E是对的,应该是Distinct Count。

SELECT Count(DISTINCT s.SID) STUDENTCOUNT,
       sd.DEPARTMENT,
       sd.REGISTRATIONDATE,
       Count(CASE
               WHEN ENROLLDATE BETWEEN REGISTRATIONDATE AND REGISTRATIONDATE + 28 THEN 1
             END) StudentInCourseCount
FROM   STUDENT S
       LEFT JOIN COURSE C
         ON S.SID = C.SID
GROUP  BY DEPARTMENT,
          REGISTRATIONDATE 

答案 1 :(得分:0)

轻微改变以上。你想要学生的明确计数和左外连接,以便学生在零时获得课程计数

SELECT COUNT(DISTINCT s.SID) StudentCount
  ,s.DEPARTMENT
  ,s.REGISTRATIONDATE
  ,COUNT(CASE
               WHEN c.ENROLLDATE BETWEEN REGISTRATIONDATE AND REGISTRATIONDATE + 28 THEN 1
             END) StudentInCourseCount
FROM STUDENT s LEFT OUTER JOIN 
  COURSE c ON s.SID = c.SID
GROUP BY s.REGISTRATIONDATE, s.DEPARTMENT