12

我试图让所有参与者在表中拥有超过 1 条记录,其中至少一条记录具有 IsCurrent = 0 和 IsActive = 1

这是我到目前为止所拥有的,但它不起作用:

    SELECT  ParticipantId 
    FROM Contact
    WHERE (IsCurrent = 0 AND IsActive = 1 AND ContactTypeId = 1)
    Group by ParticipantId
    Having COUNT(ParticipantId) > 1

此查询带回与该描述匹配的记录,但我需要与该描述匹配的所有记录,还有更多。

4

5 回答 5

10

您可以使用EXISTS

SELECT  ParticipantId 
FROM    Contact
WHERE   EXISTS
        (   SELECT  1
            FROM    Contact c2
            WHERE   c2.ParticipantID = c.ParticipantId
            AND     ContactTypeId = 1
            GROUP BY ParticipantID
            HAVING COUNT(*) > 1
            AND COUNT(CASE WHEN IsCurrent = 0 AND IsActive = 1 THEN 1 END) >= 1
        );
于 2013-11-06T19:59:35.660 回答
3

将其用作子查询并加入它:

select * from 
(
    SELECT  ParticipantId 
    FROM Contact
    WHERE (IsCurrent = 0 AND IsActive = 1 AND ContactTypeId = 1)
    Group by ParticipantId
    Having COUNT(ParticipantId) > 1
) base
inner join Contact c on c.ParticipantId = base.ParticipantID
WHERE (IsCurrent = 0 AND IsActive = 1 AND ContactTypeId = 1)
于 2013-11-06T20:01:15.283 回答
0
  SELECT  ParticipantId 
    FROM Contact
   Group by ParticipantId 
  Having Count(*) > 1 
Intersect
  SELECT  ParticipantId 
    FROM Contact
   WHERE IsCurrent = 0 
     AND IsActive = 1 
     AND ContactTypeId = 1
于 2013-11-06T20:12:50.113 回答
0
select 
  ParticipantId
from Contact as c
group by
  ParticipantId
having 
  Count(*) > 1
  and
  Sum(Case when IsCurrent = 0 then 1 else 0 end) >= 1
  and
  Sum(Case when IsActive = 1 then 1 else 0 end) >= 1

我会先试试这个

于 2013-11-06T20:07:46.987 回答
0

我认为你应该删除:

AND ContactTypeId = 1

这似乎是一个索引列

于 2013-11-06T20:08:50.547 回答