我尝试从包含一些JOINS的查询中对列进行SUM值。
示例:
SELECT
p.id AS product_id,
SUM(out_details.out_details_quantity) AS stock_bought_last_month,
SUM(order_details.order_quantity) AS stock_already_commanded
FROM product AS p
INNER JOIN out_details ON out_details.product_id=p.id
INNER JOIN order_details ON order_details.product_id=p.id
WHERE p.id=9507
GROUP BY out_details.out_details_pk, order_details.id;
我得到了这个结果:
+------------+-------------------------+-------------------------+
| product_id | stock_bought_last_month | stock_already_commanded |
+------------+-------------------------+-------------------------+
| 9507 | 22 | 15 |
| 9507 | 22 | 10 |
| 9507 | 10 | 15 |
| 9507 | 10 | 10 |
| 9507 | 5 | 15 |
| 9507 | 5 | 10 |
+------------+-------------------------+-------------------------+
现在,我想要对值进行求和,但当然有重复。我还必须按product_id进行分组:
SELECT
p.id AS product_id,
SUM(out_details.out_details_quantity) AS stock_bought_last_month,
SUM(order_details.order_quantity) AS stock_already_commanded
FROM product AS p
INNER JOIN out_details ON out_details.product_id=p.id
INNER JOIN order_details ON order_details.product_id=p.id
WHERE p.id=9507
GROUP BY p.id;
结果:
+------------+-------------------------+-------------------------+
| product_id | stock_bought_last_month | stock_already_commanded |
+------------+-------------------------+-------------------------+
| 9507 | 74 | 75 |
+------------+-------------------------+-------------------------+
想要的结果是:
+------------+-------------------------+-------------------------+
| product_id | stock_bought_last_month | stock_already_commanded |
+------------+-------------------------+-------------------------+
| 9507 | 37 | 25 |
+------------+-------------------------+-------------------------+
如何忽略重复?当然,行数可以改变!
答案 0 :(得分:4)
Select P.Id
, Coalesce(DetailTotals.Total,0) As stock_bought_last_month
, Coalesce(OrderTotals.Total,0) As stock_already_commanded
From product As P
Left Join (
Select O1.product_id, Sum(O1.out_details_quantity) As Total
From out_details As O1
Group By O1.product_id
) As DetailTotals
On DetailTotals.product_id = P.id
Left Join (
Select O2.product_id, Sum(O2.order_quantity) As Total
From order_details As O2
Group By O2.product_id
) As OrderTotals
On OrderTotals.product_id = P.id
Where P.Id = 9507
答案 1 :(得分:1)
另一种方法:
SELECT
p.product_id,
p.stock_bought_last_month,
SUM(order_details.order_quantity) AS stock_already_commanded
from
(SELECT
product.id AS product_id,
SUM(out_details.out_details_quantity) AS stock_bought_last_month,
FROM product
INNER JOIN out_details ON out_details.product_id=product.id
WHERE product.id=9507
group by product.id
) AS p
INNER JOIN order_details ON order_details.product_id=p.product_id
group by p.product_id;
严格地说,在这个例子中,group by子句是不必要的,因为只有一个产品ID - 但是,如果选择了多个产品ID,则它们是必要的。
答案 2 :(得分:0)
试试这个:
SELECT
p.id AS product_id,
SUM(DISTINCT(out_details.out_details_quantity)) AS stock_bought_last_month,
SUM(DISTINCT(order_details.order_quantity)) AS stock_already_commanded
...