我很惊讶我无法找到解决方法。我们有一张桌子
ORDER # | PRODUCT ID | PRICE 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]
这已经奏效,但强烈希望只有一个查询。
答案 0 :(得分: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
答案 1 :(得分:0)
select sum(price) as total_price where product_id=[enter here id];
答案 2 :(得分:0)
SELECT SUM(t1.price) FROM tableName t1 WHERE
t1.orderId IN (SELECT t2.orderId FROM tableName t2 WHERE
t2.productId=productIdYouWant)
如果您需要更多关于这项工作的信息,请随时提出。
答案 3 :(得分:0)
尝试:
select sum(price) as total_price
from orders
where prod_order in
(select prod_order
from orders
where product_id = 1)
检查this SQLFiddle以确认结果。
答案 4 :(得分:0)
您需要嵌套选择。内部选择应该为您提供总订单价值;
select order, sum(price) as totalvalue from table group by order
现在您需要选择产品编号为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
)