获取不符合条件的行数

时间:2013-04-17 17:36:15

标签: sql select

给出一个与客户和产品相关的简单表格(订单详细信息/历史记录类型):

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

3 个答案:

答案 0 :(得分:1)

试试这个:

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

答案 1 :(得分: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')

答案 2 :(得分:0)

您也可以使用此方法

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