【问题标题】:How to sum multiple Product Prices for a unique order如何为一个独特的订单汇总多个产品价格
【发布时间】:2015-11-09 23:35:47
【问题描述】:

我有一张包含订购商品的表格,有时我有一个包含多行的订单 ID(每个订购商品 1 行)。

OrderID | Order.Item_id | Item.Price | Quantity | OrderTotal | Seller ID |
1       | 1             | 10         | 1        | 10         |1          |
2       | 2             | 15         | 1        | 25         |1          |
2       | 3             | 10         | 1        | 25         |2          |
3       | 4             | 15         | 1        | 44         |1          |
3       | 5             | 10         | 1        | 44         |1          |
3       | 6             | 19         | 1        | 44         |2          |

我需要一种仅针对给定卖家 ID 导出/显示 OrderTotal 的方法。

理想情况下,我需要以下行中的结果:

OrderID | Order.Item_id | Item.Price | Quantity | OrderTotal | Seller ID |
1       | 1             | 10         | 1        | 10         |1          |
2       | 2             | 15         | 1        | 15         |1          |
3       | 4             | 15         | 1        | 25         |1          |
3       | 5             | 10         | 1        | 25         |1          |

在 OrderID 2 的情况下,我可以轻松地选择项目价格,但这不适用于 OrderID 3,因为我需要对两个项目求和。这是否可能仅使用 SQL。你能帮帮我吗?

提前非常感谢!

【问题讨论】:

  • 如果您添加有问题的预期输出,其他人将很容易为您提供解决方案
  • 第二张表应该是寻找的结果。感谢您的评论,我已尝试通过间距使其更加清晰。

标签: mysql sql


【解决方案1】:

您可以按订单和卖家获取订单总和,然后返回订单信息获取其他值:

select o.order_id, o.item_id, o.price, o.quantity, q.total, o.seller_id from (
  select order_id, seller_id, sum(price) total
  from   orders
  where seller_id = 1
  group by order_id, seller_id
) q
join orders o on (o.order_id = q.order_id and q.seller_id = o.seller_id);

Fiddle

【讨论】:

  • 非常感谢。有很多不同的桌子有点复杂,但这肯定会让齿轮移动。非常感谢!
【解决方案2】:

尝试如下

Select SellerID,
       OrderID,
       -- below will display the items id comma seperated
       group_concat(Itme_id) as itemlist,
       -- below will display the item price comma seperated, you can use sum(Price) also
       group_concat(Price) as pricelist,
       sum(quantity) as totalquantity,
       sum(OrderTotal) as totalorders
From Table
where SellerID = 1
group by SellerID,OrderID

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-12
    相关资源
    最近更新 更多