Sql 获取与条件不匹配的行数

Sql 获取与条件不匹配的行数,sql,select,Sql,Select,给出一个客户和产品的简单表格(订单详细信息/历史记录类): +--------------------+ | customer | product | +--------------------+ | Smith | p1 | | Smith | p3 | | Jones | p1 | | Jones | p2 | | Davis | p3 | | Davis | p9 | | Brown |

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

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

以下是使用聚合查询的一种方法:

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')

以下是使用聚合查询的一种方法:

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')
试试这个:

select customer
from MyTable
where customer not in (select customer from MyTable where Product = 'P1')
试试这个:

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

您也可以使用这种方法

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

您也可以使用这种方法

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

你的对照表是什么样子的,客户与产品关联在哪里?@Alkini nice edit-TX你的对照表是什么样子的,客户与产品关联在哪里?@Alkini nice edit-txall都是很好的答案-羞耻我不能勾选所有答案都是很好的答案-羞耻我不能勾选所有答案