过滤一个字段以完全匹配多个标准(否#34;或#34;)

时间:2015-03-06 18:44:48

标签: sql ms-access

在下表中:

pk  buyorder    code    Person  Supplier    Product
1   1   code1   person1 Supplier1   pen
2   1   code1   person1 Supplier1   pencil
3   1   code1   person1 Supplier1   computer
4   2   code2   person1 Supplier1   phone
5   2   code2   person1 Supplier1   desk
6   2   code2   person1 Supplier1   chair
7   3   code2   person1 Supplier1   phone
8   3   code2   person1 Supplier1   toy
9   3   code2   person1 Supplier1   shoes
10  3   code2   person1 Supplier1   sneakers
11  4   code3   person2 Supplier2   phone
12  4   code3   person2 Supplier2   monitor
13  4   code3   person2 Supplier2   laptop
14  5   code4   person5 Supplier2   phone
15  5   code4   person5 Supplier2   suitcase
16  5   code4   person5 Supplier2   post-it
17  5   code4   person5 Supplier2   sneakers
18  6   code4   person4 Supplier2   phone
19  6   code4   person4 Supplier2   suitcase
20  6   code4   person4 Supplier2   wallet
21  6   code4   person4 Supplier2   chair
22  7   code4   person5 Supplier2   phone
23  7   code4   person5 Supplier2   suitcase
24  7   code4   person5 Supplier2   car
25  7   code4   person5 Supplier2   laptop

我想要一个SQL查询来回答以下问题:谁订购了手机和行李箱,钱包和椅子?

更新:我正在使用MS ACCESS,它似乎不支持嵌套的DISTINCT函数。

我正在寻找的答案是BUYORDER = 6,person4。

其中一位乐于助人的人(非常感谢btw)建议我使用:

Select Person
from Table 
where product in ('phone','suitcase','wallet','chair')  
group by Person
having count( * ) = 4

但是,即使person5没有包含“wallet”和“chair”的买家订单,此查询也会返回person4和person5。

非常感谢你!

特别感谢Blam为我耐心地拼出联接! :)

2 个答案:

答案 0 :(得分:1)

select A.person
from (SELECT DISTINCT person,product FROM yourtable) A
where A.product in ('phone','suitcase','wallet','chair')  
group by A.person 
having count(*) = 4

答案 1 :(得分:0)

select person 
  from table 
 where product in ('phone','desk','char')  
 group by person 
having count(distinct(product)) = 3

您也可以使用交叉点或连接

select t1.*
  from table t1
  join table t2 
    on t2.person = t1.person 
   and t1.product = 'phone'
   and t2.product = 'desk'
  join table t3 
    on t3.person = t1.person
   and t3.product = 'char'