MySQL分组查询结果列求和问题:汇总totalcost字段值
问题
我用以下MySQL查询获取产品成本:
select SUM(strg_op.opcost)/ SUM(strg_op.opvalue * 1000) * strg_catgs.Disrate as totalcost from strg_catgs INNER JOIN strg_op on strg_op.ElemID = strg_catgs.elemID and strg_catgs.elemID =( select strg_catgs.elemID where strg_catgs.catID = '13' ) and strg_catgs.catID = '13' and strg_catgs.descr = "cwe" GROUP by strg_catgs.elemID
该查询返回结果:
| totalcost| | -------- | | 1.1 | | 5.814681 |
我需要把totalcost列的所有值求和(1.1 + 5.814681),得到单个结果:
| totalcost | | -------- | | 6.9 |
尝试嵌套SUM的查询但无效:
select sum( SUM(strg_op.opcost)/ SUM(strg_op.opvalue * 1000) * strg_catgs.Disrate ) as totalcost from strg_catgs INNER JOIN strg_op on strg_op.ElemID = strg_catgs.elemID and strg_catgs.elemID =( select strg_catgs.elemID where strg_catgs.catID = '13' ) and strg_catgs.catID = '13' and strg_catgs.descr = "cwe" GROUP by strg_catgs.elemID
求正确的求和方式。
解决方案
MySQL不允许直接在SUM()里嵌套另一个聚合函数,你需要先把原查询的结果作为子查询,再对子查询的totalcost列求和。
正确的SQL写法如下:
SELECT SUM(sub.totalcost) AS totalcost FROM ( SELECT SUM(strg_op.opcost)/SUM(strg_op.opvalue * 1000) * strg_catgs.Disrate AS totalcost FROM strg_catgs INNER JOIN strg_op ON strg_op.ElemID = strg_catgs.elemID AND strg_catgs.catID = '13' AND strg_catgs.descr = "cwe" GROUP BY strg_catgs.elemID ) AS sub;
注:原查询里的子查询strg_catgs.elemID = (select strg_catgs.elemID where strg_catgs.catID = '13')是冗余条件,外层已经有strg_catgs.catID = '13',可以直接去掉,不影响结果。
如果需要将结果四舍五入到一位小数(和示例中的6.9匹配),可以使用ROUND()函数:
SELECT ROUND(SUM(sub.totalcost), 1) AS totalcost FROM ( SELECT SUM(strg_op.opcost)/SUM(strg_op.opvalue * 1000) * strg_catgs.Disrate AS totalcost FROM strg_catgs INNER JOIN strg_op ON strg_op.ElemID = strg_catgs.elemID AND strg_catgs.catID = '13' AND strg_catgs.descr = "cwe" GROUP BY strg_catgs.elemID ) AS sub;
内容的提问来源于stack exchange,提问作者youssef kroma
相关产品推荐
相关产品推荐

