2017-09-22 153 views
1

我在使用JOIN時發生SQL SELECT語句中涉及多個SUM()函數的問題。SQL SELECT multiple SUM()error

每當我將兩個值相加在一起時,它會使另一個sum函數內的值加倍。我如何防止這種情況?

例子:SQL Fiddle - 所有的X和Y值應該是2

我使用SQLite。

回答

4

您可以使用UNION此:

SELECT id, SUM(bamount) AS BAmount, SUM(camount) AS CAmount 
FROM 
(
    SELECT a.id, SUM(b.amount) AS bamount, 0 AS camount 
    FROM a 
    LEFT JOIN b ON a.id = b.a_id 
    GROUP BY a.id 
    UNION ALL 
    SELECT a.id, 0, SUM(c.amount) AS camount 
    FROM a 
    LEFT JOIN c ON a.id = c.a_id 
    GROUP BY a.id 
) AS t 
GROUP BY id; 

updated demo

這會給你:

| id | BAmount | CAmount | 
|----|---------|---------| 
| 1 |  2 |  2 | 
| 2 |  2 |  2 | 
| 3 |  2 |  2 | 
+0

也許我錯了,但這個版本似乎更高效。 – meeeee

4

您可以嘗試在單獨的子查詢中執行聚合。這是解決雙連接(或三連等)作爲連接結果的行計數問題的一種方法。

SELECT 
    a.id, 
    t1.b_sum AS x, 
    t2.c_sum AS y 
FROM a 
LEFT JOIN 
(
    SELECT a_id, SUM(amount) AS b_sum 
    FROM b 
    GROUP BY a_id 
) t1 
    ON a.id = t1.a_id 
LEFT JOIN 
(
    SELECT a_id, SUM(amount) AS c_sum 
    FROM c 
    GROUP BY a_id 
) t2 
    ON a.id = t2.a_id;