SQL JOIN + COUNT QUERY

时间:2009-10-02 11:16:23

标签: sql join count

我正在尝试显示一个显示课程列表的表格。我想列出一个专栏,其中显示完成课程的人数,如果可能的话,还包括尚未完成该课程的人数。

我的表结构如下:

Courses
courseid | title | etc

Studying
courseid | studentid | some other fields | has_completed

理想情况下,输出应该是这样的,例如:

Course Title | some other fields | Students completed | Students not completed
Something      etc                 5                    3

我难以计算两个单独的字段。任何人都可以推荐一个好方法吗?

感谢任何建议,谢谢。

3 个答案:

答案 0 :(得分:4)

这样的事情应该做:

SELECT c.CourseID, c.Title, SUM(s.Has_Completed) Completed, SUM(1-s.Has_Completed) NotCompleted
FROM Courses c
LEFT JOIN Studying s ON c.CourseID = s.CourseID
GROUP BY c.CourseID, c.Title

答案 1 :(得分:1)

如果has_completed的值为1表示true,0表示false,则可以非常简单地解决:

SELECT c.title, SUM(s.has_completed) as completed, COUNT(studentid) - SUM(s.has_completed) as notCompleted
FROM Courses c, Studying s
where c.courseid = s.courseid
GROUP BY c.courseid, c.title 

答案 2 :(得分:0)

尝试使用SQL count command

SELECT COUNT(has_completed) FROM Studying WHERE has_completed='1'