如何使用SQL加入和求和

时间:2017-11-23 06:18:52

标签: sql join

我有三张桌子,我正试图加入。我的目标是查看每个订单,orderdateorderidcustomertotal amount of delivered items。订单中的每个唯一商品在订单明细表中都有一个单独的行,这意味着我需要在我的加入中总计总金额,但我不知道如何?

    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 个答案:

答案 0 :(得分:1)

你可以试试这个。

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;

答案 1 :(得分:0)

您可以尝试使用Sum Over option,而不需要明确

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;