2016-12-30 60 views
2

只包含价值观,我有几个办公室的ID和几个邮政编码如何选择,从一组

Office id Zip Code 
1111111  45220 
1111111  45221 
1111111  45214 
1111111  45215 
1111111  45216 
1111112  45220 
1111112  45221 
1111112  45214 
1111113  45220 
1111113  45221 
1111113  45214 
1111113  45215 

我的条件的行是选择办公ID,其中仅位于邮政编码45220,45221和45214。并且办公室ID不得包含任何其他邮政编码。在上表中,仅显示id 1111112。

+0

非常感谢您的帮助。这些真的很有帮助。我在列表中有几个邮政编码。所以我更新了我的查询,不包括“count = 3”部分。 – Sailaja

回答

0

它可能是这样的:

SELECT a.office_id 
    FROM mytable a 
      INNER JOIN mytable b 
       ON a.office_id = b.office_id 
    WHERE b.zip_code IN (45220,45221,45214) 
AND a.office_id not in 
(
    select office_id from mytable c 
    where c.zip_code NOT IN (45220, 45221, 45214) 
) 
    GROUP BY a.office_id 
    HAVING COUNT(*) = 3 
0

您可以使用子查询,并加入像这样:

SELECT office_id 
FROM your_table t1 
INNER JOIN 
    (SELECT office_id 
    FROM your_table 
    WHERE zip_code IN (45220,45221,45214) 
    GROUP BY office_id 
    HAVING COUNT(zip_code) = 3 
) t2 
ON t1.office_id = t2.office_id 
GROUP BY office_id 
HAVING COUNT(zip_code) = 3; 

您也可以使用设置操作except这样的:

SELECT office_id 
    FROM your_table 
    WHERE zip_code IN (45220,45221,45214) 
    GROUP BY office_id 
    HAVING COUNT(zip_code) = 3 
    EXCEPT 
    SELECT office_id 
    FROM your_table 
    WHERE zip_code NOT IN (45220,45221,45214); 
+0

'except'是SQL标准,而'minus'不是 –

+0

@a_horse_with_no_name已更新。谢谢。我刚才提到,因为OP没有提到DBMS – GurV

0

试试这个

select office_id from mytable where zip_code in(45220,45221,45214) group by office_id 
0
select distinct office from Locations 
where office NOT IN 
(
    select office from Locations 
    where zip NOT IN (45220, 45221, 45214) 
) 
and zip IN (45220, 45221, 45214) 
0

避免多个子查询的另一种选择,只需要对表进行一次扫描,根据所使用的DBMS的不同,该扫描可能会更快。

select office_id 
from office 
group by office_id 
having min(case when zip_code in ('45220', '45221', '45214') then 1 else 0 end) = 1 
    and count(case when zip_code in ('45220', '45221', '45214') then 1 end) = 3; 

表达case when zip_code in ('45220', '45221', '45214') then 1 else 0 end将计算为0,如果任何其他ZIP_CODE存在。这样可以过滤出所有那些有三个以上邮政编码的办公室。

count(...)则可以确保办公室没有少那么这三个邮政编码。


如果使用Postgres的,还可以使用数组聚合以简化代码:

select office_id 
from office 
group by office_id 
having array_agg(zip_code order by zip_code) = array['45214', '45220', '45221'] 

注意数组元素必须以相同的顺序['45214', '45220', '45221']是一个不同的阵列然后['45220', '45214', '45221']