我正在尝试查询以下数据集:
Customer ID Item Purchased
1234 Bread
1235 Peanut Butter
1234 Jelly
1234 Peanut Butter
1234 Jelly
5555 Peanut Butter
5555 Peanut Butter
1235 Jelly
我正在尝试获得以下预期结果:
Customer ID Item Purchased
5555 Peanut Butter
在这种情况下,我希望仅购买花生酱而没有其他东西的客户5555。
答案 0 :(得分:2)
您可以使用not exists
:
select t.*
from table t
where not exists (select 1
from table t1
where t1.Customer = t.Customer and
t1.Item <> 'Peanut Butter'
);
您也可以使用GROUP BY
子句来简化它:
select Customer
from table t
where Item = 'Peanut Butter'
group by Customer
having min(Item) = max(Item);
答案 1 :(得分:0)
SELECT DISTINCT(`customer_id`) FROM `tablename` WHERE
`customer_id` IN(SELECT COUNT(DISTINCT(`items_purchased`)) AS `c`,
`customer_id` FROM `table_name` GROUP BY `customer_id`)
AND `items_purchased` = 'PEANUT BUTTER'