选择包含多个订单项的订单,但在一个或多个订单项包含已定义的列表时则不会

时间:2013-10-18 23:10:20

标签: sql sql-server inner-join

我遇到SQL Server查询问题。我有几张表[Order](我知道,没有很好地命名)和[Order Entry]

订单输入基本上是订单上的“订单项”(因此每个订单有一个或多个)。订单输入中有各种列,其中一列是ItemID(每个订单输入只有一个ItemID。我想要一个查询,返回所有不包含一个或多个订单项的行(订单),列表中列出了ItemID。

这是我到目前为止所做的:

SELECT DISTINCT 
    oe.OrderID, StoreID
FROM 
    OrderEntry oe
INNER JOIN  
    [order] o ON o.ID = oe.OrderID 
              AND o.StoreID = oe.StoreID
              AND oe.ItemID NOT IN (60, 856, 857, 858, 902, 59, 240, 57, 217, 853, 855, 854, 41)

我想做的事情看起来与此相似(下图),但我无法弄清楚: SELECT all orders with more than one item and check all items status

请帮忙! (非常感谢)

5 个答案:

答案 0 :(得分:0)

如果我正确理解你,你想要这样的东西。使用Orders表开始查询并使用左连接将确保您获得所需的订单。通过在ItemID上匹配匹配,您可以在where语句中检查空值,以查找没有这些订单项的订单。

select distinct o.OrderID, o.StoreID
from Orders o
left join OrderEntry oe on oe.OrderID = o.ID and oe.StoreID = o.StoreID
    and oe.ItemID in (60,856,857,858,902,59,240,57,217,853,855,854,41)
where oe.OrderID is null

所以要稍微打破一下:

  • “从订单中选择不同的...”表示“从订单中获取所有内容”

  • “左连接OrderEntry on ...”表示“获取符合此条件的所有OrderEntry记录;如果没有符合条件的记录,则空值正常”

  • “oe.OrderID为null”表示“我只想查看左边连接中没有匹配的订单中的项目”

如果我们使用了内连接,那么我们就失去了“nulls are OK”部分,所以where子句不起作用。

答案 1 :(得分:0)

 SELECT DISTINCT oe.OrderID, StoreID 
 FROM OrderEntry oe 
 WHERE NOT EXISTS (SELECT * 
                  FROM [order] o 
                  WHERE o.ID = oe.OrderID AND 
                       o.StoreID = oe.StoreID AND 
                       oe.ItemID IN ( 60,856,857,858,902,59,240,57,217,853,855,854,41 ))

这是你追求的吗?

答案 2 :(得分:0)

试试这个:

select OrderId, StoreId
from Order O
where o.orderId not in (select OrderId from 
    OrderEntry d where d.ItemId IN (10,6,7,5) )

此致

答案 3 :(得分:0)

SELECT oe.OrderID, StoreID
FROM   OrderEntry oe
INNER  JOIN [order] o
ON     o.ID = oe.OrderID
AND    o.StoreID = oe.StoreID
GROUP BY oe.OrderID, StoreID
AND SUM (CASE WHEN oe.ItemID NOT IN ( 60,856,857,858,902,59,240,57,217,853,855,854,41 ) 
THEN 1 
ELSE 0
END) = 0

答案 4 :(得分:0)

我能够从你们中的几个人那里拿走一些东西(Miguel Guzman--你提供了我需要的火花)并让它发挥作用。这是我的最终查询:

SELECT o.ID, o.StoreID
FROM [Order] o
JOIN PSD_ServiceTicket st
  ON o.ID = st.WorkOrderID
  AND o.StoreID = st.StoreID
WHERE o.StoreID = 101
AND o.Time >= '10/1/2013'
AND o.Time <= '10/18/2013'
AND o.ID NOT IN (SELECT OrderID
         FROM OrderEntry oe
         INNER JOIN [order] o
            ON o.ID = oe.OrderID
            AND o.StoreID = oe.StoreID
         WHERE oe.StoreID = 101
         AND o.Time >= '10/1/2013'
         AND o.Time <= '10/18/2013'
         AND oe.ItemID IN ( 60,856,857,858,902,59,240,57,217,853,855,854,41 )
        )
AND (st.ServiceTypeID = 1 OR st.ServiceTypeID = 4 )

感谢大家!