SQL Server:选择仅包含某些值的行?

Jes*_*766 1 sql sql-server

希望有人可以帮助解决这个问题,我正在努力解决这个问题。

我有一个名为的表tblAgreements,如下所示:

AgreementID | GroupDescription |   Live
------------+------------------+--------
20549       |        h&s       |    1
20549       |    construction  |    1
20549       |        HR        |    1
20549       |      Legal       |    1
Run Code Online (Sandbox Code Playgroud)

我的目标是提取所有只有H&S 和施工组描述的协议 ID 。如果 anagreementID具有 h&s、construction 以及任何其他值(例如在我的示例中) - 它不会被拾取。仅具有 H&S、建筑或两者兼有的那些。

我的查询看起来像这样

select * 
from tblagreements 
where groupdescription in ('construction', 'h&s')
Run Code Online (Sandbox Code Playgroud)

这将带回类似于我的示例表的内容,这不是我想要的,因为该协议 ID 也有 HR/Legal 组描述

那有意义吗?希望有人能帮助我解决这个问题!

一如既往的感谢

Gio*_*sos 5

您可以使用以下查询:

select AgreementID  
from tblagreements
group by AgreementID 
having count(case when groupdescription in ('construction', 'h&s') then 1 end) >= 0 
       and 
       count(case when groupdescription not in ('construction', 'h&s') then 1 end) = 0 
Run Code Online (Sandbox Code Playgroud)

获取满足您要求的协议的 ID。然后将此查询用作连接操作中的派生表以获取其余字段。