Wednesday, 29 August 2018

The query does not return the results as expected

I have the following query

SELECT  id AS "CLIENT CODE",name AS "CLIENT NAME",(
                            SELECT
                                count(status)
                            FROM
                                campaigns
                            WHERE
                                clientid = clients.id
                            ) AS "TOTAL CAMPAIGNS"
FROM    clients
WHERE   id IN
        (
        SELECT  clientid
        FROM    campaigns
        WHERE   status IN ('L', 'P')
        )
        AND id NOT IN
        (
        SELECT  clientid
        FROM    campaigns
        WHERE   status NOT IN ('L', 'P')
        );

Now I have a clients table with all clients and a campaigns table with a status column that contains values of either L,C,P,?,X. Now one client can have 1 or more rows from campaigns. So with other words a client can have more than one campaigns with status values assigned to a campaign. Of either L,C,P,?,X
What I want the query to return to me is clients with campaigns where the status is L and P and not only P and not only L but both L and P. At the moment the query returns client that either have P or L or both.

This should ensure that it has both
WHERE   id IN
        (
        SELECT  clientid
        FROM    campaigns
        WHERE   status IN ('L')
        )
    AND id  IN
        (
        SELECT  clientid
        FROM    campaigns
        WHERE   status IN ('P')
        )

WHERE   EXISTS
        (
        SELECT  clientid
        FROM    campaigns
        WHERE   status IN ('L')
        AND     clientid = client.id
        )
    AND EXISTS
        (
        SELECT  clientid
        FROM    campaigns
        WHERE   status IN ('P')
        AND     clientid = client.id
        )

0 comments:

Post a Comment