Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 so far, but it's not working:

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

This query brings back a record that matches that description, but I need all of the records that match that description, there are more.

like image 408
user1202606 Avatar asked Nov 06 '13 19:11

user1202606


People also ask

How do you find at least one value in SQL?

The subquery is a SELECT statement. If the subquery returns at least one record in its result set, the EXISTS clause will evaluate to true and the EXISTS condition will be met. If the subquery does not return any records, the EXISTS clause will evaluate to false and the EXISTS condition will not be met.

What does having COUNT 1 mean in SQL?

In other words, COUNT(1) assigns the value from the parentheses (number 1, in this case) to every row in the table, then the same function counts how many times the value in the parenthesis (1, in our case) has been assigned; naturally, this will always be equal to the number of rows in the table.

Can you use COUNT in a WHERE clause SQL?

SQL SELECT COUNT() can be clubbed with SQL WHERE clause. Using the WHERE clause, we have access to restrict the data to be fed to the COUNT() function and SELECT statement through a condition.


2 Answers

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
        );
like image 91
GarethD Avatar answered Sep 17 '22 14:09

GarethD


Use it as a subquery and join to it:

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)
like image 40
Joel Coehoorn Avatar answered Sep 20 '22 14:09

Joel Coehoorn