sql select records having count > 1 where at lease one record has value

后端 未结 5 1945
情深已故
情深已故 2021-02-13 18:20

I\'m trying to get all participants that have more than 1 record in the table where at lease one of those records has IsCurrent = 0 and IsActive = 1

This is what I have

5条回答
  •  南旧
    南旧 (楼主)
    2021-02-13 19:03

    You can use 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
            );
    

提交回复
热议问题