SQL根据ID获得值

问题描述 投票:1回答:1
ID      DEPT
-------------
123       1
431       1
527       2
527       1
431       2
527       3
527       4

鉴于此表,我正在努力寻找一种方法来返回与所有DEPT值配对的ID为期望的结果是ID = 527

sql
1个回答
3
投票

Group by id并计算每个ID的不同dept。该数字必须与表中不同的dept的数目相同:

select id
from tablename
group by id
having count(distinct dept) = (select count(distinct dept) from tablename)

请参见demo。结果:

| id  |
| --- |
| 527 |

0
投票

您可以使用非重复计数:

   select id
      from tab
     group by id
     having count(*)=count(distinct dept)
© www.soinside.com 2019 - 2024. All rights reserved.