2015-05-04 35 views
0

我在SQL至极一个问题,我会尽量简要解释SQL:WHERE和'与'陈述的问题

TABLENAME:

Customer name | ProductClass 
----------------------------- 
A   | Accessory 
B   | Accessory 
B   | Bicycle 
C   | Bicycle 

我的目标: 仅显示客户B的2行。因此,让查询仅显示具有2个值的产品类别的产品的产品类别

如果我尝试

Select * 
From Example 
WHERE ProductClass LIKE 'Accessory' 
AND ProductClass LIKE 'Bicycle' 

我没有得到任何结果

如果我试图

Select * 
From Example 
WHERE ProductClass LIKE 'Accessory' 
OR ProductClass LIKE 'Bicycle' 

我得到的所有4行。

+4

SQL不是英语,你不应该尝试去解释它。 “AND”示例没有返回任何结果的原因是因为'ProductClass'不能同时是'Accessory'和'Bicycle'。它可以是或者但不是两者。 – Matthew

回答

1

显示谁拥有2值对ProductClass

的custumors
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] 
+2

嗯......跟我的答案完全一样 –

+0

我知道......这是一个Stack Overflow timing 。当我第一次看到这个问题时,你的答案还没有到。我写和发布我的答案,继续前进。我看到评论后回来,时间戳清楚地表明你是第一个。当您有机会看到此回复时,我会在几分钟内删除它。 –

+0

或者他会接受我的答案,这会阻止我删除它:/ –

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 
+0

我认为内部查询还应该有'WHERE'条件,WHERE'ProductClass ='Accessory'或ProductClass ='Bicycle'',否则这也可能返回行,例如'WHERE ProductClass ='SomethingElse'' – Tom

+1

不是他们要求的......他们希望拥有2种产品的所有用户不管使用哪种产品。 –

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 
) 
+0

我想他想看到两行,并且productClass列 –

+0

我已经更新了我的答案。谢谢。 – Nizam

+2

只是一个小问题'NULL'值,但我猜'客户名称'不能为空,然而,+1 –

0

如何使用SQL INTERSECT

SELECT * FROM Example WHERE ProductClass LIKE 'Accessory' 
INTERSECT 
SELECT * FROM Example WHERE ProductClass LIKE 'Bicycle' 
+0

这不起作用,因为ProductClass列在查询中会有所不同 – Nizam