2010-07-09 51 views
0

取第一次出现我有Oracle SQL查询取出由结果

select 
    distinct 
    tab1.col1, 
    tab2.col1 
from 
    table1 tab1 
    join table2 tab2 on tab1.col1 = tab2.col1 

在这里,我得到的不同的值方面的预期。

For Example : The result rows are 

1 2 
3 4 
5 6 

现在我想再为table3添加一个连接。所以我的SQL是

select 
    distinct 
    tab1.col1, 
    tab2.col1, 
    tab3.col1 
from 
    table1 tab1 
    join table2 tab2 on tab1.col1 = tab2.col1 
    join table3 tab3 on tab1.col1 = tab3.col1 

这里问题是什么是表3返回多个值。 这导致基于表3的重复行。

For Example : The result rows are 
1 2 4 
1 2 5 
3 4 1 
3 4 2 
5 6 3 

(在这里,如果你发现第1行& 2是重复和3 & 4是一式两份)

我所试图做的是对加入表3中我想获取的 第一次出现行。

+0

你能给出一个表格中的数据的例子,你得到的查询结果和你想要得到的查询结果吗? – Rene 2010-07-09 07:05:15

+0

我在 – Madhu 2010-07-09 07:10:38

+2

上添加了预期结果您的连接条件是“tab1.col1 = tab2.col1”,但您的示例结果集包含它们的不同值... 请提供创建表语句,其中包含一些示例数据和预期结果集基于该样本数据。 – 2010-07-09 07:51:01

回答

4

这个寒暄为你工作!

select 
    distinct 
    tab1.col1, 
    tab2.col1, 
    MIN(tab3.col1) 
from 
    table1 tab1 
    join table2 tab2 on tab1.col1 = tab2.col1 
    join table3 tab3 on tab1.col1 = tab3.col1 
GROUP BY tab1.col1, tab2.col1 

编辑:思考,

我假设列3是其不断增加,在这部作品中这种情况下,一个整数。您可以使用日期列来准确定义您的汇总,以获得“您的行的第一次出现”。

1
select 
    distinct 
    tab1.col1, 
    tab2.col1, 
    t3.col1 
from 
    table1 tab1 
    join table2 tab2 on tab1.col1 = tab2.col1 
    join (select distinct col1 from table3) t3 on tab1.col1 = t3.col1 
+0

如果表3有更多记录会怎么样?性能问题 – Madhu 2010-07-09 07:02:14

+0

我不知道上下文。你应该看解释计划。 – onof 2010-07-09 07:14:23

+0

-1:DISTINCT在所有列中返回不同的值 - 这只会删除所有三列的重复值。请参阅Baaju的回答,了解处理OP要求的正确方法。 – 2010-07-09 16:36:12