查询帮助:使用最大ID获取一次重复值

时间:2017-06-30 09:46:51

标签: oracle

在下面的查询中,我希望CPNY_ID只出现一次ID的最大值(在本例中为2)。最好,我不想使用任何子查询。

- 编辑开始 如果我可以改写我的问题,如果,当我用表t_main加入它时,我从表t_ref获得多个匹配。我想只从t_ref匹配最大ID值。 - 编辑完成

你能否提出更好的选择?

create table t_main (id number, org_id number, aid number);
insert into t_main values(1,100,10);
insert into t_main values(2,200,20);
insert into t_main values(3,300,30);

create table t_ref (id number, cpny_id number, bid number);
insert into t_ref values(1,100,10);
insert into t_ref values(2,100,20);
insert into t_ref values(3,300,30);
insert into t_ref values(4,500,40);

commit;

select a.id, a.org_id, b.cpny_id  from t_main a inner join t_ref b on a.aid = b.bid;

--Result
ID  ORG_ID  CPNY_ID
1     100       100
2     200       100
3     300       300

问候。

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT MAX(a.id), MAX(a.org_id), b.cpny_id 
FROM t_main a 
INNER JOIN t_ref b 
ON a.aid = b.bid
GROUP BY b.cpny_id