假设我有一个类似于以下内容的表
CUSTOMER PURCHASES
James Basketball
James Football
Alex Basketball
我如何选择只购买篮球的客户? 即只有亚历克斯。感谢您提供任何帮助或建议。
答案 0 :(得分:8)
这是使用标准SQL的一种方式;
SELECT CUSTOMER FROM Table1
GROUP BY CUSTOMER
HAVING COUNT(*) = 1
AND MAX(PURCHASES)='Basketball'
如果客户购买了多个篮球,您可以将COUNT(*)
替换为COUNT(DISTINCT Purchases)
。
如果你去了特定于数据库,一个更可读的选项可能是EXCEPT
或MINUS
,这里是一个SQL服务器版本;
SELECT CUSTOMER FROM Table1 WHERE PURCHASES='Basketball'
EXCEPT
SELECT CUSTOMER FROM Table1 WHERE PURCHASES<>'Basketball'
......这将与后者(可能购买不止一个篮球)的情况相同。
答案 1 :(得分:0)
select *
from purchase
group by customer
having count(*) = 1
and purchases = 'BasketBall';`
工作示例