连接两个表并返回一列的较大值

时间:2016-04-22 07:09:49

标签: sql oracle

最近我想出了一个场景,我有两个名为emp1和emp2的表,它有以下列和表,如下所示

table:emp1

dno  sal    
10   1000
20   2000
30   3000

table:emp 2

dno  sal    
10   4000    
20   5000   
30        

,输出表就像

table: output
dno   sal
10    4000
20    5000
30    3000

3 个答案:

答案 0 :(得分:0)

您需要加入这两个表,然后使用greatest()函数返回两个值中较大的一个。

由于薪水可以是null,您需要使用coalesce()函数将其考虑在内:

select t1.dno, greatest(coalesce(t1.sal,0), coalesce(t2.sal,0)) as sal
from emp1 t1
  join emp2 t2 on t1.dno = t2.dno;

SQLFiddle示例:http://sqlfiddle.com/#!15/bca1b/1

答案 1 :(得分:0)

根据你的评论,我认为这就是你想要的:

select e1.dno, 
     case when nvl(e1.sal,0) > nvl(e2.sal,0) then nvl(e1.sal,0) else  nvl(e1.sal,0) end as sal
from emp1 e1
inner join emp2 e2
on e1.dno = e2.dno

这是为了oracle。对于mysql,mssql,使用isnull()而不是nvl()

答案 2 :(得分:-1)

我想你想使用table2的结果 - 但是如果table2中有一个Null值你想使用table1吗?

SELECT table1.dno, NVL(table1.sal, table2.sal) 
FROM table1, table2 
WHERE table1.dno = table2.dno(+)