2013-04-17 37 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')