查询以选择同一列上具有不同值的条件

时间:2019-07-31 18:55:30

标签: sql

我必须选择属于user_id 1和2的business_type_id

例如:以下是我的桌子:

user_id     business_type_id
101             1
101             1       
101             1
101             2
101             2
102             1
102             1
103             2       
103             2
103             2

预期输出:

  

我想在两个user_id business_type_id中都找到1 & 2

结果:

  

101->是两个business_type_id中都存在的user_id。

3 个答案:

答案 0 :(得分:0)

您可以进行聚合:

select user_id
from table t
where business_type_id in (1, 2)
group by user_id
having count(distinct business_type_id) = 2;

答案 1 :(得分:0)

SELECT user_id FROM table_name WHERE business_type_id IN (1, 2) GROUP BY user_id

答案 2 :(得分:0)

如果要使user_id与business_type_id = 1或business_type_id = 2

select distinct  user_id 
from  my_table  
where business_type_id in (1,2 )

如果您希望user_id的business_type_id = 1 AND business_type_id = 2

select  user_id 
from  my_table  
where business_type_id in (1,2 )
group by user_id  
having count(distinct business_type_id ) = 2 

并且如果只希望user_id在business_type_id = 1 AND business_type_id NOT = 2的情况下

select  user_id 
from  my_table  
where user_id  not  in  (
  select distinct user_id 
  from  my_table  
  where business_type_id = 2
) 
and  business_type_id  = 1