表CMC
ID CMD USERID STATUS
1 94 4 1
2 102 24 1
3 36 32 1
4 44 40 1
5 82 2 1
6 66 27 1
7 94 56 1
8 102 2 1
表CCC
ID COURSEID CMD
1 2 94
2 16 102
3 8 82
4 5 94
5 4 66
6 8 36
7 2 56
8 19 44-
表CMD
ID COURSEID
44 5
66 3
102 16
82 5
94 8
56 4
66 2
36 19
Iam尝试使用状态计算创建一个sql查询:
COUNT(CMC.USERID) COURSED COMPLETED INPROCESS NOTSTARTED
已完成:如果该特定课程的COUNT(CMC)== COUNT(CCC)
INPROCESS:如果COUNT(CMC)> 0,但不等于COUNT(CCC)
NOTSTARTED:如果COUNT(CMC)= 0
有人建议我使用以下查询:
SELECT count(cmc.userid),
(SELECT count(ccc.id) FROM ccc HAVING count(cmc.userid) = count(ccc.id) ) AS "completed"
(SELECT count(ccc.id) FROM ccc HAVING count(cmc.userid) >0 AND count(ccc.id) !== count(cmc.userid) ) AS "Inprocess"
(SELECT count(ccc.id) FROM ccc HAVING count(cmc.userid) = 0 ) AS "Notstarted"
FROM
cmc
WHERE status = 1
答案 0 :(得分:0)
我通常更喜欢在子选择语句中执行摘要。然后我可以更轻松地排除故障。这是完成的查询(如果我理解你的问题):
SELECT UserId,
CASE WHEN CMCount=CCCount THEN 1 ELSE 0 END AS Completed,
CASE WHEN CMCount>0 and CMCount<>CCCount THEN 1 ELSE 0 END AS InProcess,
CASE WHEN CMCount=0 THEN 1 ELSE 0 END AS NotStarted
FROM (
SELECT CMC.USERID AS UserId, COUNT(CMC.CMD) AS CMCount, COUNT(CCC.CMD) AS CCCount
FROM CMC LEFT JOIN CCC ON CMC.CMD=CCC.CMD
GROUP BY CMC.USERID
) AS Summary