2016-04-22 80 views
-1

最近,我来到了这里我有两个表名为EMP1和EMP2方案,它具有以下的列和表看起来像下面连接两个表并返回一列的更大价值

表:EMP1

dno sal  
10 1000 
20 2000 
30 3000 

表:EMP 2

dno sal  
10 4000  
20 5000 
30   

和输出表就像

table: output 
dno sal 
10 4000 
20 5000 
30 3000 
+0

你想用'dno'连接2个表,并为每个匹配的'max(sal)'得到? –

+0

其实我的一个朋友想出了一个场景......但是,我们必须加入两张桌子,并为匹配得到一个最大值(sal)。@ NayruLove – Lohith

回答

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

+0

感谢好友@a_horse_with_no_name完美工作...... – Lohith

-1

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

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

请停止使用旧的,古老的和过时的隐式连接'子句 - **尤其是**外连接。即使Oracle建议停止使用专有的“(+)”运算符。 –

+0

感谢朋友的回复 – Lohith

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()

+1

Oracle _uses_ SQL。所以“*在SQL和Oracle *中”都没有意义。 –

+1

谢谢你的回复...... :) – Lohith