首页 > 解决方案 > 两个聚合函数的Mysql总和不起作用

问题描述

您好我想添加两个聚合函数的结果,但我得到“组函数的无效使用”。任何人都可以更正以下查询:

SELECT   mc.complaint_type_id,
         mc.complaint_type,
         sum(sum(case when c.is_solved = 1 then 1 else 0 end) + sum(case when ((c.is_solved = 0) and (c.res_user_id is null)) then 1 else 0 end)) as complaints_count,

    from  svk_apt_master_complaints mc
        left join svk_apt_complaints c on c.complaint_type_id = mc.complaint_type_id and c.is_active = 1
            and c.customer_id = 1 and c.association_id = 1

        group by mc.complaint_type_id

标签: mysqlsumaggregate

解决方案


尝试这个:

SELECT   mc.complaint_type_id,
         mc.complaint_type,
         sum(case when c.is_solved = 1 then 1 else 0 end) + sum(case when ((c.is_solved = 0) and (c.res_user_id is null)) then 1 else 0 end) as complaints_count
from  svk_apt_master_complaints mc
left join svk_apt_complaints c on c.complaint_type_id = mc.complaint_type_id 
where c.is_active = 1 and c.customer_id = 1 and c.association_id = 1
group by mc.complaint_type_id, mc.complaint_type

sum()使用运算符时不需要+。另外,SUM是聚合函数。

此外,您选择未包含在聚合中的列:mc.complaint_type。您需要将其包含在其中group by还是仅将其删除。


推荐阅读