SQL组函数

时间:2015-08-23 08:22:09

标签: mysql sql

我试图通过使用SUM()来计算三列,当我执行查询时,它说“#1111 - 无效使用组功能'”。我尝试纠正组功能,即使它显示错误。

我需要完整的2,3,4列

SELECT c.name, 

    SUM(CASE WHEN COUNT(distinct cmc.id) = COUNT(distinct ccc.id) THEN 1 ELSE 0 END) AS "COND1",
    SUM(CASE WHEN COUNT(distinct cmc.id) > 0 AND COUNT(distinct cmc.id) != COUNT(distinct ccc.id) THEN 2 ELSE 0 END) AS "COND2",
    SUM(CASE WHEN COUNT(distinct cmc.id) = 0 THEN 3 ELSE 0 END) AS "COND3"

    FROM
    lesson_modules_completion cmc
    INNER JOIN lesson_modules cm ON cmc.lessonmoduleid = cm.id
    INNER JOIN lesson_completion_settings ccc ON cm.lesson = ccc.lesson 
    INNER JOIN lesson c ON cm.lesson = c.id
    INNER JOIN user u ON u.id = cmc.userid
    WHERE ccc.criteriatype=4
    GROUP BY c.name

我需要每个用户的计数包括每个课程的已完成模块,Inprocess模块​​和未启动模块,其中通过从表CM获取课程来获取表CC中的用户ID计数,获取用户已完成的模块数量当然。

(一门课程可以有一个以上的模块,一门课程可以让所有模块的用户数量很少,很少有模块或者根本没有尝试过。)

所以,我需要一些用户 - 已经完成了一些模块 - 在课程中。 (3逻辑)

(COND1 ie,Completed.Users):如果尝试的模块数等于表CMS中的modinstance数(例如:每个课程用户尝试的模块数= 9,no.modinstance = 9.因为7不等于9,它们完成了。)

(COND2 ie,Inprocess.Users):尝试的模块数应该> 0,但不等于[每个课程的count(modinstance)](例如:每个课程用户尝试的模块数= 7, no.modinstance = 9.因为7不等于9,所以它们是Inprocess。)

(COND2,即Nostart.Users):尝试的模块数应该等于0,(例如:用户每个课程尝试的模块数= 0。它们是未启动的。)

你可以参考我的查询,这一切都很好,但我需要COND1,COND2,COND3的计数

我需要OUTPUT:

 lesson        COND1              COND2                  COND3
 5              65                 32                       6
 6              40                 12                       15
 8              43                 56                       0
 9               0                 7                        9

1 个答案:

答案 0 :(得分:0)

select lesson,sum(COND1) as COND1, sum(COND2) as COND2,sum(COND3) as COND3
from
(
SELECT c.name, 
       ccc.lesson,
    CASE WHEN COUNT(distinct cmc.id) = COUNT(distinct ccc.id) THEN 1 ELSE 0 END AS "COND1",
    CASE WHEN COUNT(distinct cmc.id) > 0 AND COUNT(distinct cmc.id) != COUNT(distinct ccc.id) THEN 2 ELSE 0 END AS "COND2",
    CASE WHEN COUNT(distinct cmc.id) = 0 THEN 3 ELSE 0 END AS "COND3"

    FROM
    lesson_modules_completion cmc
    INNER JOIN lesson_modules cm ON cmc.lessonmoduleid = cm.id
    INNER JOIN lesson_completion_settings ccc ON cm.lesson = ccc.lesson 
    INNER JOIN lesson c ON cm.lesson = c.id
    INNER JOIN user u ON u.id = cmc.userid
    WHERE ccc.criteriatype=4
    GROUP BY c.name,ccc.lesson
) t
group by lesson