2

假设我有一张如下所示的表格

CUSTOMER     PURCHASES
James        Basketball
James        Football
Alex         Basketball

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

4

2 回答 2

8

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

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

一个用于测试的 SQLfiddle

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

如果您使用特定于数据库的选项,则更易读的选项可能是EXCEPTMINUS,这里是 SQL 服务器版本;

SELECT CUSTOMER FROM Table1 WHERE PURCHASES='Basketball'
EXCEPT
SELECT CUSTOMER FROM Table1 WHERE PURCHASES<>'Basketball'

...这将与后者(可能购买了多个篮球)箱做同样的事情。

于 2013-10-07T04:32:47.473 回答
0
select * 
from purchase 
group by customer 
having count(*) = 1 
   and purchases = 'BasketBall';`

工作示例

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

于 2013-10-07T04:37:05.167 回答