2012-01-02 25 views
6
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 

sản lượng hiện tạiLàm thế nào để làm tổng của tổng trong truy vấn mysql

supplier total_qty 
12046  475.00 
12482  99.00 

đầu ra cần thiết

total_qty 
574.00 

đây tôi cần sự sum (total_qty) trong truy vấn này? làm thế nào để đạt được điều này

+1

Bạn có cần nó như là một tiện ích hàng itional trong cùng một kết quả? Hay bạn muốn chạy một SELECT thứ hai? –

+1

yup @a_horse_with_no_name – Ghostman

+2

* yup * cái gì? Tôi hỏi hai câu hỏi. –

Trả lời

14

Chỉ việc điều chỉnh GROUP BY, thêm 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 
+2

+1 Tìm hiểu điều gì đó mới mỗi ngày - VỚI ROLLUP - cảm ơn! – dash

+1

cảm ơn hoàn hảo ... – Ghostman

+2

+1 --Tôi hoàn toàn bỏ lỡ rằng MySQL đã VỚI ROLLUP quá! Tôi đã sử dụng nó rất nhiều trong MSSQL 2005. Làm việc như một sự quyến rũ! – Nonym

3

thử

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 - SAU bình luận từ OP thay đổi cấu trúc kết quả:

Đối với một thử cột bổ sung:

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 

Đối với hàng additonal:

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

thế nào về điều này:

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 
1

thử mà không sử dụng nhóm bởi vì bạn muốn tổng hợp tất cả các điều

+0

chỉ để lại phần 'GROUP BY' sẽ dẫn đến thông báo lỗi ... – Yahia

+0

tại sao lại như vậy? lỗi nào – redmoon7777

Các vấn đề liên quan