简体   繁体   中英

How to do sum of sum in mysql query

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

output present

supplier    total_qty
12046      475.00
12482      99.00

output needed

total_qty
574.00

here i need the sum(total_qty) in this query? how to achieve this

Just modify GROUP BY , adding 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

Output:

supplier    total_qty
12046       475.00
12482        99.00
NULL        574.00

how about this:

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

try

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'

EDIT 2 - AFTER comment from OP changing the result structure:

For an additional column try:

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

For an additonal row:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM