我在SQL中遇到问题我将尝试简要解释
TABLENAME:示例
Customer name | ProductClass
-----------------------------
A | Accessory
B | Accessory
B | Bicycle
C | Bicycle
我的目标: 仅显示客户B的2行。因此,让查询仅显示具有2个ProductClass值的客户
如果我尝试
Select *
From Example
WHERE ProductClass LIKE 'Accessory'
AND ProductClass LIKE 'Bicycle'
我没有结果
如果我尝试
Select *
From Example
WHERE ProductClass LIKE 'Accessory'
OR ProductClass LIKE 'Bicycle'
我得到了所有4行。
答案 0 :(得分:4)
Select [Customer name]
From Example
group by [Customer name]
having count(distinct ProductClass) > 1
如果你想获得整行,那么你可以使用
SELECT *
FROM Example
WHERE [Customer name] in (
Select [Customer name]
From Example
group by [Customer name]
having count(distinct ProductClass) > 1
)
答案 1 :(得分:1)
试试这个:
SELECT * FROM Example e
INNER JOIN (
Select CustomerName, COUNT(*) AS ProdClassCount
From Example
GROUP BY CustomerName
HAVING COUNT(*) = 2 -- OR Maybe > 1
) x ON x.CustomerName = e.CustomerName
答案 2 :(得分:1)
显示具有2个ProductClass值的客户
SELECT *
FROM Example e
INNER JOIN
(
select [customer name]
from example
group by [customer name]
having count(*) = 2
) c on c.[customer name] = e.[customer name]
答案 3 :(得分:0)
如何使用SQL INTERSECT?
SELECT * FROM Example WHERE ProductClass LIKE 'Accessory'
INTERSECT
SELECT * FROM Example WHERE ProductClass LIKE 'Bicycle'