如何在mysql查询中求和的总和

时间:2012-01-02 11:54:09

标签: mysql sql

SELECT a.id AS supplier, sum( processed_weight ) AS total_qty
FROM supplier_inward a
INNER JOIN warehouseb ON a.id = b.supplier
WHERE a.master_product_id = '38'
GROUP BY b.supplier

输出现在

supplier    total_qty
12046      475.00
12482      99.00

需要输出

total_qty
574.00

这里我需要这个查询中的总和(total_qty)?如何实现这个

4 个答案:

答案 0 :(得分:16)

只需修改GROUP BY,添加 WITH ROLLUP

SELECT a.id AS supplier, sum( processed_weight ) AS total_qty
FROM supplier_inward a
  INNER JOIN warehouseb ON a.id = b.supplier
WHERE a.master_product_id = '38'
GROUP BY b.supplier
  WITH ROLLUP

输出:

supplier    total_qty
12046       475.00
12482        99.00
NULL        574.00

答案 1 :(得分:4)

怎么样:

SELECT SUM(iQuery.total_qty) as iTotal
FROM
    (SELECT a.id AS supplier, sum( processed_weight ) AS total_qty
    FROM supplier_inward a
    INNER JOIN warehouseb ON a.id = b.supplier
    WHERE a.master_product_id = '38'
    GROUP BY b.supplier) as iQuery

答案 2 :(得分:3)

SELECT sum( processed_weight ) AS total_qty
FROM supplier_inward a
INNER JOIN warehouseb ON a.id = b.supplier
WHERE a.master_product_id = '38'

编辑2 - OP改变结果结构后的评论:

对于其他专栏,请尝试:

SELECT 
X.supplier,
X.total_qty,
(SELECT sum( processed_weight ) 
 FROM supplier_inward a
 INNER JOIN warehouseb ON a.id = b.supplier
 WHERE a.master_product_id = '38') AS totalq
FROM
(
SELECT 
a.id AS supplier, 
sum( processed_weight ) AS total_qty, 
FROM supplier_inward a
INNER JOIN warehouseb ON a.id = b.supplier
WHERE a.master_product_id = '38'
GROUP BY b.supplier) AS X

对于附加行:

SELECT 
a.id AS supplier, 
sum( processed_weight ) AS total_qty
FROM supplier_inward a
INNER JOIN warehouseb ON a.id = b.supplier
WHERE a.master_product_id = '38'
GROUP BY b.supplier
UNION ALL
SELECT null, X.total_qty
FROM
( 
SELECT sum( processed_weight ) AS total_qty
FROM supplier_inward a
INNER JOIN warehouseb ON a.id = b.supplier
WHERE a.master_product_id = '38' ) AS X

答案 3 :(得分:1)

尝试不使用小组,因为你想要总结每件事