繁体   English   中英

SQL查询-订单总和包含一个项目

[英]SQL Query - Sum of Order tha Contain an Item

令我惊讶的是我还没有找到解决方案。 我们有一张桌子

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]

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

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

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
select sum(price) as total_price where product_id=[enter here id];
SELECT SUM(t1.price) FROM tableName t1 WHERE 
t1.orderId IN (SELECT t2.orderId FROM tableName t2 WHERE 
                t2.productId=productIdYouWant)

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

尝试:

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

检查此SQLFiddle以确认结果。

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

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

现在,您需要选择产品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
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM