SQL Server:选择仅包含特定值的行?

时间:2018-01-04 14:47:53

标签: sql sql-server

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

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

AgreementID | GroupDescription |   Live
------------+------------------+--------
20549       |        h&s       |    1
20549       |    construction  |    1
20549       |        HR        |    1
20549       |      Legal       |    1

我的目标是提取所有 H& S和建筑群描述的协议ID。如果agreementID具有h& s,构造以及任何其他值(如我的示例中) - 它将无法被接收。只有那些有H& S,建筑或两者兼而有之。

我的查询看起来像这样

select * 
from tblagreements 
where groupdescription in ('construction', 'h&s')

这会带回类似于我的示例表的内容,这不是我想要的内容,因为还有该协议ID的HR / Legal groupdescriptions

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

一如既往地谢谢

5 个答案:

答案 0 :(得分:3)

您可以使用以下查询:

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 

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

答案 1 :(得分:0)

h&s列中查找construnctionGroupDescription的总计数和点数。然后选择同时将AgreementID计为2的{​​{1}}。

<强>查询

;with cte as (
    select [AgreementID]
    , count(*) as [total]
    , sum(case [GroupDescription] 
          when 'h&s' then 1
          when 'construction' then 1
          else 0 end
    ) as [count]
    from [t]
    group by [AgreementID]
)
select [AgreementID]
from cte
where [total] = 2 and [count] = 2;

答案 2 :(得分:0)

试试这个:

select * from tblagreements t1
where groupdescription in ('construction', 'h&s')
and not exists 
     (select * 
     from tblagreements t2 where 
     t1.AgreementID=t2.AgreementID
     and groupdescription not in ('construction', 'h&s'))

答案 3 :(得分:0)

以下解决方案提供了具有'h&amp; s'和'构造'的数字的协议,但没有任何其他

;with cte as (
    select *
    from tblAgreements
    where GroupDescription in ('h&s' , 'construction') 
), cnts as (
    select cte.AgreementID, count(*) over (partition by cte.AgreementID) as cnt
    from cte
    inner join tblAgreements as a on a.AgreementID = cte.AgreementID and a.GroupDescription = cte.GroupDescription
)
select *
from cte where AgreementID in (
    select AgreementID from cnts where cnt = 2
)

答案 4 :(得分:-1)

SELECT * FROM tblagreements
WHERE GroupDescription='H&S';

试试这个。仅提取输出&#39; H&amp; S&#39;

的Groupdesription列中的数据