社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  DATABASE

两个聚合函数的mysql和不工作

Kiran Kumar • 7 年前 • 1515 次点击  

嗨,我想添加两个聚合函数的结果,但我得到了“组函数的无效使用”。是否可以更正以下查询:

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
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/30481
文章 [ 3 ]  |  最新文章 7 年前
Kamil Gosciminski
Reply   •   1 楼
Kamil Gosciminski    7 年前

移除嵌套 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

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

fa06
Reply   •   2 楼
fa06    7 年前

您需要在group by中指定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
Michał Turczyn
Reply   •   3 楼
Michał Turczyn    7 年前

试试这个:

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 或者把它取下来。