SQL - ALL,包括所有值

时间:2014-05-01 01:11:31

标签: sql sybase-iq

我有两张桌子:

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')

现在,我想写一个查询,其中所有四个account_number 1, 2, 3, 5都包含在Campaign_id中。

答案是C.

[我的目的是找到包含account_number 1,2,3& 5.此条件仅由广告系列代码C满足。]

我尝试使用INALL,但无法使用。能帮忙吗?

3 个答案:

答案 0 :(得分:1)

我认为你所追求的是一种内在的联系。不确定您的问题是哪种方式需要您的数据。但是,这应该为您提供一个很好的线索,如何进行处理以及在文档中锁定哪些关键字以便更进一步。

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

编辑:

似乎我误解了原来的问题..抱歉。为了得到你想要的东西你可以做:

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

如果您想进一步调查,这称为关系部门。

答案 1 :(得分:1)

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

答案 2 :(得分:0)

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);

警告:t-sql实现