1

给定一个包含客户和产品的简单表格(订单详细信息/历史记录之类的东西):

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

我想列出所有从未订购过产品p1的客户,即上述数据集中的Davis

这是我开始的地方,但当然,它不起作用,我想不出下一步该去哪里:

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

3 回答 3

1

试试这个:

select customer
from MyTable
where customer not in (select customer from MyTable where Product = 'P1')
于 2013-04-17T17:40:56.897 回答
0

You can also use this approach

 SELECT t.CustomerName
 FROM Table t
 WHERE NOT EXISTS (SELECT 1 
                   FROM Table t2 
                   WHERE t2.CustomerName = t.CustomerName
                   AND t2.ProductName = 'p1')
于 2013-04-17T17:47:09.973 回答
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')
于 2013-04-17T17:40:08.760 回答