Pregunta

I have two tables:

create table xyz
(campaign_id varchar(10)
,account_number varchar)

Insert into xyz
values ( 'A', '1'), ('A', '5'), ('A', '7'), ('A', '9'), ('A', '10'),
       ( 'B', '2'), ('B', '3'),
       ( 'C', '1'), ('C', '2'), ('C', '3'), ('C', '5'), ('C', '13'), ('C', '15'),
       ('D', '2'), ('D', '9'), ('D', '10')


create table abc
(account_number varchar)

insert into abc
values ('1'), ('2'), ('3'), ('5')

Now, I want to write a query where all the four account_number 1, 2, 3, 5 are included in a Campaign_id.

The answer is C.

[My aim is to find the Campaign Code that includes account_number 1, 2, 3 & 5. This condition is only satisfied by campaign code C.]

I tried using IN and ALL, but don't work. Could you please help.

¿Fue útil?

Solución

I think what you are after is a inner join. Not sure from your questions which way around you want your data. However this should give you a good clue how to procede and what keywords to lock for in the documentation to go further.

SELECT a.*
FROM xyz a
INNER JOIN abc b ON b.account_number = a.account_number;

EDIT:

Seems I misunderstood the original question.. sorry. To get what you want you can just do:

SELECT  campaign_id
FROM    xyz 
WHERE   account_number IN ('1', '2', '3', '5')
GROUP BY campaign_id
HAVING  COUNT(DISTINCT account_number) = 4;

This is called relational division if you want to investigate further.

Otros consejos

SELECT campaign_id
FROM (
    SELECT campaign_id, COUNT(*) AS c, total_accounts
    FROM xyz
    JOIN abc ON xyz.account_number = abc.account_number
    CROSS JOIN (SELECT COUNT(*) AS total_accounts
                FROM abc) AS x
    GROUP BY campaign_id
    HAVING c = total_accounts) AS subq

DEMO

select xyz.campaign_id
from xyz
join abc
on xyz.account_number = abc.account_number
group by xyz.campaign_id
having count(xyz.campaign_id) = 
(select count(account_number) from abc);

Caution: t-sql implementation

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top