如何在MySQL的不同子查询中添加SUM?JOIN ( SELECT SUM(IF(isPurchased='0', 1, 0)) AS numQuotes, customer_id FROM product1_quote GROUP BY customer_id ) p1q ON (p1q.customer_id = c.customer_id)
JOIN ( SELECT SUM(IF(isPurchased='0', 1, 0)) AS numQuotes, customer_id FROM product2_quote GROUP BY customer_id ) p1q ON (p1q.customer_id = c.customer_id)
所以我想将这两个加起来,并将numQuotes作为总数numQuotes。但是,这要复杂得多,因为不同表的数量是动态的,因此在任何给定情况下都可以有任意数量的子查询。
最佳答案
以下是什么?
select sum(numQuotes), customer_id from
(
(SELECT SUM(IF(isPurchased='0', 1, 0)) AS numQuotes, customer_id FROM
product1_quote GROUP BY customer_id ) p1q ON (p1q.customer_id = c.customer_id)
UNION
(SELECT SUM(IF(isPurchased='0', 1, 0)) AS numQuotes, customer_id FROM
product2_quote GROUP BY customer_id ) p1q ON (p1q.customer_id = c.customer_id)
) group by customer_id;
括号可能已关闭,因此请先检查它们。
关于mysql - 如何将来自不同子查询的多个SUM加到一个结果中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3626336/