如何在oracle join中只根据列值获取一条记录

时间:2015-02-17 07:28:08

标签: sql oracle select

enter image description here

加入table1时,我只需要为列值1获取一条记录,有人可以告诉我这是否可以在Oracle中实现?

目前我有

join (select * from table2 where column1='1') tab2result
on table1.column1 = tab2result.column1.

加入时我只需要第一条不同column1值的记录。

2 个答案:

答案 0 :(得分:1)

您可以在子查询中使用聚合max(或min)函数:

SELECT t1.colum1, t1.column2, t2.column1, t2.column2
FROM   table1 t1
JOIN   (SELECT   column1, MAX(column2) AS column2
        FROM     table2
        GROUP BY column1) t2 ON t1.column1 = t2.column1

答案 1 :(得分:1)

基本上,

Select t1.column1
     , t1.column2
     , t2first.column2
  From table t1
  Join (
           Select row_number() over (partition by t2.column1 order by t2.column2) AS rn
                , t2.column1
                , t2.column2
             from table t2
       ) t2first on ( t2first.column1 = t1.column1 )
 where t2first.rn = 1
     ;