简体   繁体   English

SQL Server查询以按订单查找所有产品的总价

[英]SQL Server query to find the total price of all the products by order

I have a table Orders with (id,orderCode,productId,quantity,color,size) where I can have entries like: 我有一个具有(id,orderCode,productId,quantity,color,size)的表Orders,其中我可以输入以下内容:

1,O20100812,163,2,BLUE,Medium
1,O20100812,163,3,BLUE,Larger
1,O20100812,145,4,RED,Large etc
1,O20100815,134,5,RED,Large etc
1,O20100815,143,2,BLACK,Large etc
1,O20100815,112,8,BLACK,Large etc

And another table Products with (id,name,price) 另一个具有(id,name,price)表Products

What I want is to find the total price of all the products in the order with orderCode 020100812. Should I DISTINCT select the order code and then SUM the quantity while JOINing the products table? 我想要的是使用orderCode 020100812查找订单中所有产品的总价。我是否应该先选择订单代码,然后在加入产品表时求和求和?

Why you need distinct? 为什么需要与众不同?

Select SUM(o.Quantity * Price) TotalPrice
FROM Orders o JOIN Products p ON (o.ProductId = p.Id)
WHERE OrderCode = '020100812'

For all orders you can use the following query: 对于所有订单,您可以使用以下查询:

Select OrderCode, SUM(o.Quantity * Price) TotalPrice
FROM Orders o JOIN Products p ON (o.ProductId = p.Id)
Group by OrderCode

No, GROUP BY and then you can use SUM to aggregate across the group, eg 不, GROUP BY ,然后您可以使用SUM汇总整个组,例如

select  O.id, O.ordercode, sum(P.price * O.quantity) as total
  from  orders O
  join  products P on P.id = O.productid
group by O.id, O.ordercode

which will show you the total price for each order code within each order - if you wanted all order codes across all orders you'd need 这将为您显示每个订单中每个订单代码的总价格-如果您需要跨所有订单的所有订单代码

select  O.ordercode, sum(P.price * O.quantity) as total
  from  orders O
  join  products P on P.id = O.productid
group by O.ordercode

ie don't group in the order ID. 即不要分组订单ID。

(I'm guessing that O20100812 was just an example and you actually want this for all order codes?) (我猜测O20100812只是一个示例,您实际上是否希望所有订购代码都使用它?)

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

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