sql选择记录有计数> 1其中至少有一条记录具有价值

时间:2013-11-06 19:56:22

标签: sql sql-server tsql

我正在尝试让所有参与者在表中有超过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

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

5 个答案:

答案 0 :(得分:9)

您可以使用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
        );

答案 1 :(得分: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)

答案 2 :(得分: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

我会先试试这个

答案 3 :(得分:0)

我认为你应该删除:

AND ContactTypeId = 1

似乎是一个列出的列

答案 4 :(得分: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