2013-04-17 40 views
1

給出一個簡單的表格(訂單明細/歷史類的話)行數和產品:獲取與客戶不匹配標準

+--------------------+ 
| customer | product | 
+--------------------+ 
| Smith | p1  | 
| Smith | p3  | 
| Jones | p1  | 
| Jones | p2  | 
| Davis | p3  | 
| Davis | p9  | 
| Brown | p1  | 
| Brown | p2  | 
| Brown | p5  | 
+----------+---------+ 

我想列出從未訂購的產品所有客戶p1,即戴維斯在上述數據集。

這是我開始,但是,當然,它不工作,我不能想到哪兒去旁邊:

select 
    customer, 
    count(*) as c 
where product='p1' 
    and c = 0 
+1

什麼是你的對照表看看比如,客戶與產品相關聯的地方? –

+0

@Alkini很好的編輯 - tx – pm100

回答

0

這裏有一種方法,使用聚合查詢:

select customer 
from t 
group by customer 
having sum(case when product = 'p1' then 1 else 0 end) = 0 

這給你表中的所有客戶。如果你有客戶的單獨列表,那麼你可以使用:

select customer 
from customerTable 
where customer not in (select customer from t where product = 'p1') 
1

嘗試了這一點:

select customer 
from MyTable 
where customer not in (select customer from MyTable where Product = 'P1') 
+0

都是很好的答案 - 可惜我不能打勾所有人 – pm100

0

您也可以使用這種方法

SELECT t.CustomerName 
FROM Table t 
WHERE NOT EXISTS (SELECT 1 
        FROM Table t2 
        WHERE t2.CustomerName = t.CustomerName 
        AND t2.ProductName = 'p1')