如何将SQL子查询中的所有记录求和以检索所有记录的总和?

时间:2018-01-24 14:10:58

标签: sql sum subquery

我正在编写查询以检索用于制作产品的所有组件价格的总和,但我对此查询有疑问。我编码查询以检索每个组件的价格(使用的数量*单价)我检索到正确的结果:

SELECT t1.coc_codigo, SUM(t1.pmc_precio) * SUM(t2.ccm_cantidad)
FROM   precios_componentes_costos t1
JOIN   composicion_tipos_masa t2
ON     (t1.coc_codigo = t2.coc_codigo)
WHERE  t1.coc_codigo IN (SELECT coc_codigo
                         FROM   composicion_tipos_masa t3
                         JOIN   tipos_masas t4
                         ON    (t3.tms_codigo =t4.tms_codigo)
                         WHERE  t3.tms_codigo = 'MMS')
GROUP BY t1.coc_codigo
ORDER BY 1 ASC;

enter image description here enter image description here

但是当我尝试总结所有记录时,我检索到错误的结果:

SELECT SUM(t1.pmc_precio) * SUM(t2.ccm_cantidad) AS TOTAL
FROM   precios_componentes_costos t1
JOIN   composicion_tipos_masa t2
ON     (t1.coc_codigo = t2.coc_codigo)
WHERE  t1.coc_codigo IN (SELECT coc_codigo
                         FROM   composicion_tipos_masa t3
                         JOIN   tipos_masas t4
                         ON    (t3.tms_codigo =t4.tms_codigo)
                         WHERE  t3.tms_codigo = 'MMS')
ORDER BY 1 ASC;

enter image description here

我想用查询检索最终结果(195.591132)。你有什么主意吗?谢谢!

2 个答案:

答案 0 :(得分:1)

与@ PM77-1的观察结果一致,您需要在获得总和之前对每个记录执行计算。像这样:

SELECT
    coc_codigo
  , SUM(TOTAL_SUB) AS TOTAL
FROM (
    SELECT
          t1.coc_codigo
        , (t1.pmc_precio * t2.ccm_cantidad) AS TOTAL_SUB
    FROM precios_componentes_costos t1
    INNER JOIN composicion_tipos_masa t2
        ON ( t1.coc_codigo = t2.coc_codigo )
    INNER JOIN composicion_tipos_masa t3
        ON ( t3.tms_codigo = t1.coc_codigo )
    INNER JOIN tipos_masas t4
        ON ( t3.tms_codigo = t4.tms_codigo )
    WHERE t3.tms_codigo = 'MMS'
    GROUP BY t1.coc_codigo
 ) AS multiplied

答案 1 :(得分:1)

最后来自@ PM77-1的评论让我重新制作了我的查询,新的查询是:

SELECT /*t1.coc_codigo,*/ SUM(t1.pmc_precio * t2.ccm_cantidad)
FROM   precios_componentes_costos t1
JOIN   composicion_tipos_masa t2
ON     (t1.coc_codigo = t2.coc_codigo)
WHERE  t1.coc_codigo IN (SELECT coc_codigo
                         FROM   composicion_tipos_masa t3
                         JOIN   tipos_masas t4
                         ON    (t3.tms_codigo =t4.tms_codigo)
                         WHERE  t3.tms_codigo = 'MMS')
--GROUP BY t1.coc_codigo
ORDER BY 1 ASC;

这个查询是正确的!!!谢谢大家的帮助。