SQL SELECT * WHERE值NOT IN列表和IN另一个列表

时间:2014-10-20 09:07:29

标签: sql notin

我想选择一个不在('DC01','5000')的SKU,但是在('1003','1039','1012')中,SUM大于3.我打算获取零记录,因为SKU'000000001041106003'在'1003'且StockOnHand大于3,但StoreID为'DC01',但返回了SKU值'000000001041106003'。该SKU的StoreID为“DC01”和“1003”。

为了获得理想的结果,我需要做些什么?

productName                    SKU  StoreId StockOnHand webenabled

.Speedo Yarn    000000001041106001  1003        1         1
.Speedo Yarn    000000001041106002  1003        3         1
.Speedo Yarn    000000001041106003  1003        4         1
.Speedo Yarn    000000001041106003  DC01        0         1


SELECT DISTINCT(SKU)
FROM etlStoreAssortment 
WHERE StoreId NOT IN ('DC01','5000') 
AND StoreId IN ('1003','1039','1012') GROUP BY SKU HAVING SUM(StockOnHand) > 3

1 个答案:

答案 0 :(得分:1)

WHERE查看单个记录。那里的一条记录,用于&00; 000000001041106003' StoreId NOT IN(' DC01',' 5000')和StoreId IN(' 1003',' 1039',' 1012& #39)。你要找的是每组至少有一条记录有或没有特定价值的地方。使用HAVING:

SELECT DISTINCT(SKU)
FROM etlStoreAssortment 
GROUP BY SKU 
HAVING SUM(StockOnHand) > 3
AND MAX(CASE WHEN StoreId IN ('DC01','5000') THEN 1 ELSE 0 END) = 0
AND MAX(CASE WHEN StoreId IN ('1003','1039','1012') THEN 1 ELSE 0 END) = 1;