子查询返回多个值

时间:2019-01-16 00:56:17

标签: sql sql-server

SELECT TOP 100 PERCENT  
    dbo.Customers.Company, 
    MAX(dbo.Orders.ShipDate) AS Expr1,
    (SELECT dbo.OrderItems.Price FROM dbo.OrderItems) AS Expr2
FROM 
    dbo.Customers
INNER JOIN 
    dbo.Orders ON dbo.Customers.CustomerID = dbo.Orders.CustomerID
INNER JOIN 
    dbo.OrderItems ON dbo.Orders.OrderID = dbo.OrderItems.OrderID
WHERE 
    (dbo.Orders.Deleted = 0)
GROUP BY 
    dbo.OrderItems.InvMasID, dbo.Customers.Company

我正在尝试从与外部查询中调用的相关dbo.OrderItems.Price相关的dbo.Orders.ShipDate中提取价格。我的查询不断抛出错误,指出内部查询返回的值不止1个。

我的问题是,我将如何让内部查询只提取与外部查询要提取的值匹配的值。

2 个答案:

答案 0 :(得分:0)

您需要确定如何合并公司订单上所有不同的价格。我不知道你要什么例如,以下代码返回所有价格的总和:

printf

答案 1 :(得分:0)

如果您解释您想要哪个客户订单,以及您想要整个订单价格还是该订单中每个项目的价格,我们可以更加具体。我不得不做一些假设(请参阅评论):

select
      c.Company
    , o.ShipDate as this_is_max_ship_date_of_customer 
    , o.OrderID --Added OrderID so you know what the price is associated with
    , sum(oi.price) this_is_sum_of_prices_of_the_order
                --if you want the price of a particular item, you can add ItemID beneath OrderID and also group by it
from dbo.Customers c
join dbo.Orders o
    on c.CustomerID = o.CustomerID
join dbo.OrderItems oi
    on o.OrderID = oi.OrderID
where o.Deleted = 0
    and o.ShipDate in (select max(inner_o.ShipDate) from dbo.Orders inner_o
                       where inner_o.Company = c.Company
                       group by inner_o.Company)
                       --This subquery points to the outer reference - a useful trick
                       -- it means only the most recent ShipDate for the customer is shown
    and o.OrderId in (select max(inner_o2.OrderId) from dbo.Orders inner_o2
                       where inner_o2.Company = c.Company
                         and inner_o2.ShipDate = o.ShipDate
                       group by inner_o2.Company)
                       --This subquery is doing the same thing, but for your OrderId
                       --Unfortunately you don't specify enough in your question, so
                       --  I have to assume you only want their most recent order
                       --To prevent an ShipDate that is not of the OrderId you care about,
                       --  I had to add the second where clause here
group by
    c.Company,
    o.ShipDate,
    o.OrderId