每个商店都没有的产品

时间:2014-08-14 16:21:22

标签: sql sql-server

我有一个表格列表

产品

{  ProdID (INT),  Name(varchar),   ...}

商品

{ StoreID(INT), Location(varchar), ...}

广告

 {StoreID(INT) references Store(StoreID) ,ProdID(INT) references Products(ProdID),...}

我想要每个商店都没有的产品列表

3 个答案:

答案 0 :(得分:1)

;WITH CTE
AS (
    SELECT P.ProdID 
         , S.StoreID
    FROM Product P CROSS JOIN Store S
   )
SELECT C.StoreID, C.ProdID
FROM CTE C
WHERE NOT EXISTS (SELECT 1
                  FROM Inventory
                  WHERE C.StoreID = StoreID 
                   AND  C.ProdID  = ProdID) 

答案 1 :(得分:0)

然后,您要选择库存中没有产品的所有商店。

select s.StoreID, p.ProdID, p.Name
  from Store s, (select ProdID, Name 
                   from Product
                  where ProdID not in (select i.ProdID 
                                         from inventory i
                                        where i.StoreID = s.StoreID
                                      )
                ) p
 order by s.StoreID, p.Name

答案 2 :(得分:0)

试试这个:

SELECT 
    productID, count_storeID
FROM
    (SELECT
        productid,
        COUNT(DISTINCT storeid) AS count_storeID
    FROM
        inventory
    GROUP BY 
        productID) i FULL OUTER JOIN
    (SELECT COUNT(*) AS count_stores FROM storeID   ) s
WHERE
    count_storeID < count_stores