加入多个COUNT列

时间:2014-03-20 17:48:05

标签: sql join count

course_modules
id course
1   3
2   3
3   6
4   8
5   8
23  9
46  9

user_completed_modules
id  coursemoduleid userid 
1        1           6
2        2           6
3        3           6
4        4           12
5        5           12
6        23          12
7      46          12

I need the output like

userid  course count(coursemoduleid) count(coursemodules)
 6       3               12               10
 6       8               8                10
 6       9               6                15

我需要users completed modulescount of modules in a course  我非常抱歉我的英语。

任何人都可以帮我查询吗?

SELECT count(cm.id) AS "coursemodules",
(SELECT count(cmc.coursemoduleid) FROM user_completed_modules cmc 
JOIN course_modules cm ON cmc.coursemoduleid = cm.id 
WHERE cmc.userid = 6 AND cm.course = 8 ) AS "completedmodules"
ROM course_modules cm WHERE cm.course= 8

1 个答案:

答案 0 :(得分:0)

尝试:

SELECT userid, cm.course, count(*), m.ct
     FROM user_completed_modules c JOIN
          course_modules cm ON cm.id = c.coursemoduleid JOIN
          (
            SELECT course, count(*) AS ct
               FROM course_modules GROUP BY course
          ) AS m ON cm.course = m.course
     GROUP BY userid, course, m.ct