假设我有这两张桌子:
|Customers | |Purchases |
---------------- -----------------
|CusID |----- |PurchaseID |
|CusName | |---<|CusID |
|CusAge | |ItemName |
|CusDateAdded | |DatePurchased |
我需要用多个项目名筛选我的结果集。假设我想退还所有购买“相机”和“电话”的18至24岁客户。我可以运行以下查询以获取年龄范围内客户的所有记录:
SELECT CusID
FROM Customers AS C
JOIN Purchases AS P
ON C.CusID = P.CusID
WHERE C.CusAge BETWEEN 18 AND 24
但是,当需要对purchases表中的itemname列进行筛选时,一个如何对多行进行筛选?假设没有多个查询是可能的?
最佳答案
SELECT C.CusID
FROM Customers AS C
JOIN Purchases AS P ON C.CusID = P.CusID
WHERE C.CusAge BETWEEN 18 AND 24
AND ItemName IN ('camera','phone')
GROUP BY C.CusID
HAVING count(distinct ItemName) = 2
按客户分组并仅返回同时具有这两个项目的项目。