SQL获取结果,其中列值在其他列中具有相同的值

时间:2015-12-16 20:51:53

标签: sql

大家好我无法弄清楚如何编写查询,这将返回将提供者ID分配给所有操作员ID的结果。

 operatorid-providerid
1     [1]  - [3]   
2     [2]  - [1]  
3     [3]  - [2]   
4     [1]  - [3]   
5     [2]  - [2]   
6     [3]  - [1]   
7     [1]  - [2]   
8     [2]  - [3]   
9     [3]  - [1]   
10    [1]  - [5]
11    [2]  - [5]

预期结果:

       operator-provider
    1     [1]  - [3]   
    2     [2]  - [1]  
    3     [3]  - [2]   
    4     [1]  - [3]   
    5     [2]  - [2]   
    6     [3]  - [1]   
    7     [1]  - [2]   
    8     [2]  - [3]   
    9     [3]  - [1]   
未显示

providerid 5,因为它未分配给operatorid 3

我尝试了很多选项,但这里没有成功是最后一次查询。我会发布代码,但它没有意义。

代码:

SELECT t2.operatoriausID,t2.papildomosPaslaugosID
FROM OperatoriausPapildomaPaslauga t2,
(SELECT t5.papildomosPaslaugosID,count(t5.papildomosPaslaugosID) c
FROM OperatoriausPapildomaPaslauga t5
group by t5.papildomosPaslaugosID) d
WHERE d.c = 3

3 个答案:

答案 0 :(得分:2)

with cte1 as 
(  select distinct(operatorid) from table ) 
,    cte2 as 
(  select providerid 
     from table 
     join cte1 
       on cte1.operatorid = table.operatorid 
    group by providerid 
   having count(distinct(table.operatorid)) = ( select count(*) from cte1 )
)
select table.* 
  from table 
  join cte2 
    on table.providerid = cte2.providerid 

或者这甚至可能有效

select table.* 
  from table 
  join ( select providerid 
           from table 
          group by providerid 
         having count(distinct(operatorid)) = ( select count(distinct(operatorid)) 
                                                  from table )
       ) tt
    on table.providerid = tt.providerid 

答案 1 :(得分:1)

select table.*
from table
where table.providerID in (
    select table.providerID
    from table
    group by table.providerID
    having count(distinct table.operatorID) = 
         (select count(distinct table.operatorID) 
          from table)
    )

答案 2 :(得分:0)

尝试使用not exists谓词:

with cte as(select distinct(operatorid) o from table)
select * from table t1
where not exists(select * from cte c 
                 left join table t2 on c.o = t2.operatorid and 
                                       t1.providerid = t2.providerid 
                 where t2.providerid is null)