SQL - 尝试对各个订单求和

时间:2014-12-02 15:48:14

标签: sql

我有一个数据库,其中包含:

  • 1位客户可以下订单
  • 1订单可包含多个订单项

我所拥有的表格

  • 客户
  • 订单
  • 订单项

我想生成一个报告,向我显示通过添加订单项计费的订单的价值。

当我尝试

SELECT Customers.CustomerNumber, Orders.OrderNumber, 
    SUM(LineItems.ItemPrice * LineItems.QuantityOrdered) AS 'Order Value'
FROM LineItems.ItemNumber
WHERE Customers.CustomerNumber = '1234'
GROUP BY Orders.OrderNumber, Customers.CustomerNumber

这似乎给了我个人订单,但它给了我客户所有订单的总价值。

有没有办法单独显示每个订单的价值而不是所有订单的总和?

更新

SELECT
    Agreement.AgreementNumber AS 'Agreement Number', 
    POBase.PurchaseOrderNumber AS 'Purchase Order Number',
    SUM(POLI.UsedPrice * POLI.QuantityOrdered) AS 'Billed Amount'

FROM MyDatabase..PurchaseOrderLineItemBase AS POLI
INNER JOIN 
    MyDatabase..AgreementBase AS Agreement
    ON POLI.AgreementKey = Agreement.AgreementKey
INNER JOIN
    MyDatabase..PurchaseOrderBase AS POBase
    ON POLI.AgreementKey = POBase.AgreementKey
WHERE 
    (Agreement.AgreementNumber = '1234'
    OR Agreement.AgreementNumber =  '234')
    AND POLI.POLineItemStatusName = 'Invoiced'
GROUP BY 
    POBase.AgreementKey,
    POBase.PurchaseOrderNumber,
    Agreement.AgreementNumber
ORDER BY 
    Agreement.AgreementNumber

2 个答案:

答案 0 :(得分:3)

您的查询没有意义,因为您列出的表不在from子句中。试试这个:

SELECT o.CustomerNumber, o.OrderNumber, 
       SUM(li.ItemPrice * li.QuantityOrdered) AS 'Order Value'
FROM orders o JOIN
     LineItems li
     ON o.OrderNumber = li.OrderNumber
WHERE o.CustomerNumber = '1234'
GROUP BY o.OrderNumber, o.CustomerNumber;

假设CustomerNumberOrders表中,您不需要CUstomers表。

答案 1 :(得分:-1)

当然,如果按CustomerNumber分组,它会这样做。摆脱GROUP BY中的CustomerNumber以获取所有订单。