1

我很惊讶我无法找到解决方案。我们有一张桌子

订单号 | 产品编号 | 价格
   1 | 1 | 1.00
   1 | 2 | 2.00
   2 | 3 | 3.00
   2 | 4 | 4.00
   3 | 1 | 5.00
   3 | 4 | 6.00

我们想要获取包含 productID=1 的所有订单的收入总和。这个例子中的结果应该是 1+2+5+6 = 14

实现这一目标的最佳方法是什么?

目前,我最好的解决方案是运行两个查询。
1 -SELECT orderID FROM table WHERE prodID=$prodID

2 -SELECT price FROM table WHERE orderID=[result of the above]

这已经奏效,但强烈希望有一个查询。

4

5 回答 5

1

这是一个查询,可提供您正在寻找的结果:

SELECT OrderNum, SUM(PRICE) as TotalPrice
FROM MyTable AS M
WHERE EXISTS (SELECT 1 -- Include only orders that contain product 1
              FROM MyTable AS M2 
              WHERE M2.OrderNum=M.OrderNum AND M2.ProductId=1)
GROUP BY OrderNum
于 2013-08-09T14:46:30.183 回答
0
select sum(price) as total_price where product_id=[enter here id];
于 2013-08-09T14:44:19.753 回答
0
SELECT SUM(t1.price) FROM tableName t1 WHERE 
t1.orderId IN (SELECT t2.orderId FROM tableName t2 WHERE 
                t2.productId=productIdYouWant)

如果您需要有关此工作原理的更多信息,请随时询问。

于 2013-08-09T14:52:44.647 回答
0

尝试:

select sum(price) as total_price
from orders
where prod_order in
       (select prod_order
       from orders
       where product_id = 1)

检查此 SQLFiddle以确认结果。

于 2013-08-09T14:53:24.860 回答
0

您需要一个嵌套选择。内部选择应该给你总订单价值;

select order, sum(price) as totalvalue from table group by order

现在您需要选择product id为1的订单,然后将订单价格相加;

select sum(totalvalue) from (
  select order, sum(price) as totalvalue from table group by order
) where order in (
  select order from table where productid = 1
)
于 2013-08-09T14:53:31.447 回答