SQL:如何选择仅购买某种产品的用户?

时间:2013-10-07 04:26:22

标签: sql

假设我有一个类似于以下内容的表

CUSTOMER     PURCHASES
James        Basketball
James        Football
Alex         Basketball

我如何选择只购买篮球的客户? 即只有亚历克斯。感谢您提供任何帮助或建议。

2 个答案:

答案 0 :(得分:8)

这是使用标准SQL的一种方式;

SELECT CUSTOMER FROM Table1
GROUP BY CUSTOMER
HAVING COUNT(*) = 1
  AND MAX(PURCHASES)='Basketball'

An SQLfiddle to test with

如果客户购买了多个篮球,您可以将COUNT(*)替换为COUNT(DISTINCT Purchases)

如果你去了特定于数据库,一个更可读的选项可能是EXCEPTMINUS,这里是一个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';`

工作示例

http://www.sqlfiddle.com/#!2/fe6ee/1