2014-10-20 132 views
0

我想選擇一個不在('DC01','5000')中但在('1003','1039','1012' ),其中SUM大於3.我打算取回零記錄,因爲SKU'000000001041106003'在'1003'且StockOnHand大於3,但具有'DC01'的StoreID,但是SKU值'000000001041106003' '返回。該SKU具有「DC01」和「1003」的StoreID。SQL SELECT * WHERE value NOT IN list and IN another list

爲了獲得理想的結果,我需要做些什麼?

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 
+0

林不知道哪個方言你正在使用,但無論如何我會寫「......不是 IN ......」等等「......不是STOREID IN(......」 。 – user2504380 2014-10-20 09:12:39

+1

根據數據和您的查詢,輸出是正確的。每個記錄根據條件單獨驗證。 – 2014-10-20 09:12:58

回答

1

WHERE查看單個記錄。有其中StoreId NOT IN('DC01','5000')和StoreId IN('1003','1039','1012')的'000000001041106003'的一條記錄。但是,您要查找的是每個組中至少有一條記錄具有或沒有特定值的位置。使用具有本:

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; 
+0

感謝您的幫助。 – 2014-10-20 09:24:41