MySQL:获取每一行的总计,然后获取每个“分组依据”的总计

时间:2019-08-22 12:15:47

标签: mysql

对不起,标题,我不知道使用什么合适的术语。

我有此数据:

enter image description here

我想产生一个像这样的表:

enter image description here

我想获取每个“分组依据”的总数,我正在执行此代码,但总数却有误。

SELECT code, (a * b)
AS total_each_code
FROM  table1   
GROUP BY code 

更新:更新了示例数据的照片,对于错别字很抱歉。

2 个答案:

答案 0 :(得分:2)

您可以为此使用子查询

select code, sum(a.total_each_code)
         from (
            SELECT code, (a * b)
                AS total_each_code
                FROM  table1   order by code
                )a 
        group by a.total_each_code

或简单

select code,sum(a*b) as total from table1 group by code.

答案 1 :(得分:2)

使用sum()聚合

SELECT code, sum(a * b)
AS total_each_code
FROM  table1   
GROUP BY code