我尝试从包含一些连接的查询中对列中的值进行求和。
示例:
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 |
+------------+-------------------------+-------------------------+如何忽略重复项?当然,行数可以改变!
发布于 2010-07-28 00:43:56
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 发布于 2010-07-28 01:09:13
另一种方法:
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,则它们将是必需的。
https://stackoverflow.com/questions/3345657
复制相似问题