简体   繁体   中英

SQL - Trying to sum individual orders

I have a database in which:

  • 1 customer can place many orders
  • 1 Order can contain many line items

the tables I have are

  • Customers
  • Orders
  • Line Items

I want to generate a report that shows me the value of the Orders that have been billed by adding the Line Items.

When I try

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

This seems to give me the individual orders but it gives me the total value of all orders the customer has placed.

Is there a way to show the value of each order individually not the sum of all orders placed?

Update

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

Your query doesn't make sense, because you have tables listed that are not in the from clause. Try this:

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;

Assuming that CustomerNumber is in the Orders table, you don't need the CUstomers table.

Of course, if you group by CustomerNumber it will do so. Get rid of the CustomerNumber in GROUP BY to get all the Orders.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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