MS SQL Table Joins - Multiple Tables

时间:2015-08-07 01:43:58

标签: sql-server join

I am new to MS SQL and am having trouble joining 4 tables within a query.

I am trying to join Orders, Order Lines, Client, and Picked tables to create a query to show quantity ordered and picked for a client. If I comment out the last inner join for Picked, I get the correct results. When I include the inner join for Picked the query returns results but data that should be in the Picked fields is NULL. One order line can have 1 or more Picked lines.

SELECT          W_Warehouse, OH.OrderID, OH.RequiredDate,   C.Client, OL.LineNbr, OL.QtyOrd, P.QtyPick
FROM            Order
INNER JOIN      Warehouse on Order.OH_WHS = Warehouse.W_PK
INNER JOIN      Client on Order.O_Client = Client.C_PK
INNER JOIN      OrderLine on Order.O_PK = OrderLine.OL_PK
INNER JOIN      Picked on OrderLine.O_PK = Picked.P_PK
WHERE           C.CLIENT = 'WENDYS'

2 个答案:

答案 0 :(得分:0)

如果不知道表格中的数据,就很难准确回答。

但正如您所说,Picked表中有1行以上,您可能希望使用GROUP BY和SUM()进行聚合

答案 1 :(得分:0)

也许这就是你要找的东西:

SELECT
    W.W_Warehouse, 
    OH.OrderID, 
    OH.RequiredDate,
    C.Client,
    OL.LineNbr,
    OL.QtyOrd,
    P.QtyPick
FROM
    Order OH
    INNER JOIN Warehouse W on OH.OH_WHS = W.W_PK
    INNER JOIN Client C on OH.O_Client = C.C_PK
    INNER JOIN OrderLine OL on OH.O_PK = OL.OL_PK
    CROSS APPLY (
        select sum(QtyPick) as QtyPick
        from Picked P
        where OL.O_PK = P.P_PK
    ) P
WHERE
    C.CLIENT = 'WENDYS'

它分别计算QtyPick的总和,因此它不会增加结果中的行数。