如何检查一列中的值是否与另一列中的特定数量的值匹配?

时间:2018-01-12 18:31:37

标签: sql sql-server

我正在努力寻找只有三种水果的医生,这些水果对所有医生来说都很常见 - Apple,Kiwi和Orange。以下是我提取数据的代码:

source = [......]
indexes = [.......]
filteredByIndexes = [source[i] for i in indexes]

给出

的结果
SELECT Doctor AS [Dr Name], Fruit_Staff_Map.ID AS [Physician ID], fruit.Name

FROM Staff

INNER JOIN Fruit_Staff_Map ON Staff.staffKey=Fruit.staffKey
INNER JOIN Fruit ON Fruit_Staff_Map.fruitKey=Fruit.fruitKey

WHERE
Staff.isActive = 'true'

如你所见,每个医生都有猕猴桃,橙子和苹果。我希望医生只有猕猴桃,橙子和苹果。因此,我的结果应该如下:

Dr Name    Physician ID Fruit
Dr Helga    94233       apple
Dr Helga    94233       orange
Dr Helga    94233       strawberry
Dr Helga    94233       blueberry
Dr Helga    94233       kiwi
Dr Robert   95555       orange
Dr Robert   95555       apple
Dr Robert   95555       kiwi
Dr James    94074       apple
Dr James    94074       kiwi
Dr James    94074       orange
Dr James    94074       strawberry
Dr James    94074       blueberry
Dr James    94074       apple
Dr James    94074       banana
Dr Helga    96552       kiwi
Dr Helga    96552       orange
Dr Helga    96552       apple
Dr Tania    93688       kiwi
Dr Tania    93688       apple
Dr Tania    93688       banana
Dr Tania    93688       orange

我在尝试解决这个问题时遇到了多个问题。对我来说,最大的障碍是如何排除拥有超过这三种水果的医生。

2 个答案:

答案 0 :(得分:0)

一种选择是添加一个IN条件来过滤3个水果,添加分区Row_Number()来识别拥有超过这三个水果的医生。

     SELECT [Dr Name] ,
            [Physician ID] ,
            fruitName
     FROM   ( SELECT    Doctor AS [Dr Name] ,
                        Fruit_Staff_Map.ID AS [Physician ID] ,
                        fruit.NAME fruitName ,
                        ROW_NUMBER() OVER ( PARTITION BY Doctor, fruit.NAME ORDER BY Doctor ) ctr
              FROM      Staff
                        INNER JOIN Fruit_Staff_Map ON Staff.staffKey = Fruit.staffKey
                        INNER JOIN Fruit ON Fruit_Staff_Map.fruitKey = Fruit.fruitKey
              WHERE     Staff.isActive = 'true'
                        AND fruit.NAME IN ( 'kiwi', 'orange', 'apple' )
            ) T
     WHERE  ctr = 1

答案 1 :(得分:0)

Hmmmm。您可以通过以下方式获得所有医生的共同成果:

select fs.fruitKey
from fruit_staff fs
group by fs.fruitKey
having count(*) = (select count(*) from staff where isActive = 'true')

然后,您可以使用group_concat()将其合并到查询中以比较列表:

select s.doctor
from staff s join
     fruit_staff fs
     on s.staffkey = fs.staffkey
group by s.doctor
having group_concat(fs.fruitKey order by fs.fruitkey) = 
        (select group_concat(fruitkey order by fruitkey)
         from (select fs.fruitKey
               from fruit_staff fs
               group by fs.fruitKey
               having count(*) = (select count(*) from staff where isActive = 'true')
              ) fs
        );