0

I got three tables that I'm trying to join together. My goal is to see of each order, its orderdate, orderid, customer and the total amount of delivered items. Each unique item in a order get a separate line in the order details table which means that I need to sum the total amount in my join but I don't know how?

    SELECT Orders.OrderDate
        , Orders.OrderID
        , Customers.CustomerName
        , OrderDetails.Quantity AS "Deliverd products"

    FROM Orders INNER JOIN Customers ON Customers.CustomerID = Orders.CustomerID
    INNER JOIN Orderdetails ON Orders.OrderID = OrderDetails.OrderID
    ORDER BY CustomerName;

2 Answers 2

1

You can try this.

SELECT Orders.OrderDate,
       Orders.OrderID,
       Customers.CustomerName,
       SUM(OrderDetails.Quantity) AS "Deliverd products"
FROM Orders
INNER JOIN Customers ON Customers.CustomerID = Orders.CustomerID
INNER JOIN Orderdetails ON Orders.OrderID = OrderDetails.OrderID
GROUP BY Orders.OrderDate,
       Orders.OrderID,
       Customers.CustomerName
ORDER BY CustomerName;
Sign up to request clarification or add additional context in comments.

2 Comments

It worked, is there a reason why you are grouping on OrderDate and CustomerName? I just grouped on OrderID.
You have to group all columns that used in select except used in the aggregate functions.
0

You can try with Sum Over option where you do not need group by explicitly

declare @orders table(orderid int identity (1,1), orderdate datetime, customerid int)
declare @orderdetails table(orderdetailsid int identity (1,1), orderid int, quantity int)
declare @customers table(customerid int identity (1,1), customername varchar(100))

insert into @orders values('2017-11-21' , 1)
insert into @orderdetails values (1,20) ,(1,5) , (1,7)
insert into @customers values('ajay')


SELECT distinct o.OrderDate,
       o.OrderID,
       c.CustomerName

       SUM(od.Quantity) OVER (ORDER BY od.OrderID) 
FROM @orders o
INNER JOIN @customers c ON c.CustomerID = o.CustomerID
INNER JOIN @orderdetails od ON o.OrderID = od.OrderID

ORDER BY CustomerName;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.