我需要我的查询返回超过3位客户购买商品的地方。但是,我的查询一直返回Null

时间:2018-04-25 00:15:32

标签: sql sql-server

我已确认有3个SEPERATE客户购买商品的次数超过3次。但是,我的代码一直在返回Null。我已经尝试了以下代码的几种不同变体,但我得到Null或错误消息,说明"不明确的列名称' Customer_ID'。"

我也试过别名,但没有运气。我哪里错了?

   SELECT First_Name, Last_Name, Country, Address, State, Zip, Product_Name

   FROM Orders

   JOIN Customer ON Orders.Customer_ID = Customer.Customer_ID
   JOIN Amazon_Inventory ON Orders.Inventory_ID = Amazon_Inventory.Inventory_ID
   JOIN Shipment ON Amazon_Inventory.Shipment_ID = Shipment.Shipment_ID
   JOIN Product ON Shipment.Product_ID = Product.Product_ID
   JOIN Product_Listing ON Product.Listing_ID = Product_Listing.Listing_ID

   WHERE ORDER_ID IN 
       (SELECT Customer_ID, Inventory_ID 
       FROM Orders 
           GROUP BY Customer_ID, Inventory_ID 
           HAVING COUNT (Order_ID) >3 AND COUNT (INVENTORY_ID) >3); 

3 个答案:

答案 0 :(得分:0)

错误发生在IN子查询上,您无法使用IN来比较多个字段。

如果我理解正确,你可能会期待这一点。

你可以提供一些样本数据并期待结果。我会编辑我的答案。

SELECT First_Name, Last_Name, Country, Address, State, Zip, Product_Name
FROM Orders
JOIN Customer ON Orders.Customer_ID = Customer.Customer_ID
JOIN Amazon_Inventory ON Orders.Inventory_ID = Amazon_Inventory.Inventory_ID
JOIN Shipment ON Amazon_Inventory.Shipment_ID = Shipment.Shipment_ID
JOIN Product ON Shipment.Product_ID = Product.Product_ID
JOIN Product_Listing ON Product.Listing_ID = Product_Listing.Listing_ID
WHERE Customer.Customer_ID IN 
   (SELECT Customer_ID
   FROM Orders 
       GROUP BY Customer_ID
       HAVING COUNT (1) >3 ); 

答案 1 :(得分:0)

你快到了。我建议你在你的表中使用别名(这样可以解决模糊的错误),而且,你使用IN引用的SELECT选择了超过1列(提示:我会尽可能使用EXISTS而不是IN - 但情况并非如此 - 或者至少它与提供的信息似乎不一样。)

所以,使用别名我最终会得到这样的东西:

SELECT * /* Place appropriate alias in each field selected => First_Name, Last_Name, Country, Address, State, Zip, Product_Name */ FROM Orders AS OR JOIN Customer AS CU ON Orders.Customer_ID = Customer.Customer_ID JOIN Amazon_Inventory AS AI ON Orders.Inventory_ID = Amazon_Inventory.Inventory_ID JOIN Shipment AS SH ON Amazon_Inventory.Shipment_ID = Shipment.Shipment_ID JOIN Product AS PR ON Shipment.Product_ID = Product.Product_ID JOIN Product_Listing AS PL ON Product.Listing_ID = Product_Listing.Listing_ID WHERE EXISTS (SELECT 1 FROM Orders OREX WHERE OREX.Inventory_ID = OR.Inventory_ID GROUP BY OREX.Customer_ID, OREX.Inventory_ID HAVING COUNT(1)>3);

答案 2 :(得分:0)

我在想这样的事情:

SELECT 
    c.Customer_ID, i.Inventory_ID,
    c.First_Name, c.Last_Name, c.Country, c.Address, c.State, c.Zip,
    p.Product_Name
FROM Orders o
    JOIN Customer c         ON o.Customer_ID = c.Customer_ID
    JOIN Amazon_Inventory i ON o.Inventory_ID = i.Inventory_ID
    JOIN Shipment s         ON i.Shipment_ID = s.Shipment_ID
    JOIN Product p          ON s.Product_ID = p.Product_ID
    JOIN Product_Listing l  ON p.Listing_ID = l.Listing_ID
)
WHERE Inventory_ID IN (
    SELECT Inventory_ID
    FROM Orders JOIN Customer ON Orders.Customer_ID = Customer.Customer_ID
    GROUP BY Inventory_ID 
    HAVING COUNT (DISTINCT Customer_ID) > 3
);