[英]Get a count of rows not matching criteria
給定一個帶有客戶和產品的簡單表格(訂單明細/歷史記錄):
+--------------------+
| 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 MyTable
where customer not in (select customer from MyTable 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 t.CustomerName
FROM Table t
WHERE NOT EXISTS (SELECT 1
FROM Table t2
WHERE t2.CustomerName = t.CustomerName
AND t2.ProductName = 'p1')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.