Mysql两个聚合函数的总和不起作用

时间:2018-10-03 09:42:37

标签: mysql sum aggregate

嗨,我想添加两个聚合函数的结果,但是我收到“无效使用组函数”的信息。任何人都可以纠正以下查询:

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

3 个答案:

答案 0 :(得分:2)

尝试一下:

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中还是将其删除。

答案 1 :(得分:1)

您需要在分组依据中指定mc.complaint_type列

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 and c.is_active = 1 and c.customer_id = 1 and c.association_id = 1
group by mc.complaint_type_id,mc.complaint_type

答案 2 :(得分:1)

删除嵌套的sums并将mc.complaint_type添加到GROUP BY子句中。如果需要添加两个聚合函数的值,请使用+运算符,而不要使用聚合函数。

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 
  and c.is_active = 1
  and c.customer_id = 1 
  and c.association_id = 1
GROUP BY mc.complaint_type_id, mc.complaint_type

我还重新格式化了您的代码,并删除了不必要的括号。

相关问题