Oracle SQL - 加入并拥有

问题描述 投票:0回答:1

我正在尝试获取在合约表中多次出现的帐户,而不管它在 c_map 表中加入的次数。

CREATE TABLE cntrct (
  cntrct_id VARCHAR(10),
  account_id varchar(10)
);
CREATE TABLE c_map (
  cntrct_id VARCHAR(10)
);


INSERT INTO cntrct VALUES (1,'a');
insert into cntrct values (2,'b');
insert into cntrct values (3,'c');
insert into cntrct values (4,'b');

INSERT INTO c_map VALUES (1);
INSERT INTO c_map VALUES (1);
INSERT INTO c_map VALUES (1);
insert into c_map values (2);
insert into c_map values (2);
insert into c_map values (2);
insert into c_map values (3);
insert into c_map values (3);
insert into c_map values (3);
commit;

select ct.account_id
from cntrct ct, c_map cm
where ct.cntrct_id = cm.cntrct_id
group by ct.account_id
having count(ct.account_id)> 1

小提琴: http://sqlfiddle.com/#!4/cec1b7/4

我期待输出:

 b

但是我得到了所有这些。我如何限制它,以便在运行 having count()>1 时不考虑 c_map 表?

谢谢,

sql oracle inner-join having
1个回答
3
投票

获取合约表中多次出现的账户,不管它在c_map表中被加入的次数。

为什么要加入?你要的信息在合约表里:

select account_id
from cntrct 
group by account_id
having count(*) > 1

也许你想过滤地图表中存在的合同ID的数据集。如果是这样,我会推荐

exists

select account_id
from cntrct c
where exists (select 1 from c_map m where m.cntrct_id = c.cntrct_id)
group by account_id
having count(*) > 1
© www.soinside.com 2019 - 2024. All rights reserved.