使用union以自己的顺序显示数据

时间:2014-04-29 07:10:47

标签: oracle oracle11g

我想要展示 all emps who are seniors to king and who are juniors to smith按以下顺序排列。

谁是国王的前辈在国王头下,而史密斯的后辈都在史密斯头下

我试过这个,

select ename from emp where hiredate<(select hiredate from emp where ename='king')
union
select ename from emp where hiredate>(select hiredate from emp where ename='smith');

OUTPUT只有一个标题(ENAME)

如何获得所需的输出(两个标题KING SMITH) 任何人都可以帮助我

2 个答案:

答案 0 :(得分:0)

添加另一个人工柱是一个小技巧:

select 1 status, ename from emp
where hiredate<(select hiredate from emp where ename='king')
union all
select 2 status, ename from emp
where hiredate>(select hiredate from emp where ename='smith')
order by 1;

您甚至可以使用union all代替union,因为所有行都会有所不同。或者,如果你真的需要标题/分隔符:

select 0 status, 'KING''S SENIORS' from dual
union all
select 1 status, ename from emp where hiredate<(select hiredate from emp where ename='king')
union all
select 2 status, 'SMITH''S JUNIORS' from dual
union all
select 3 status, ename from emp where hiredate>(select hiredate from emp where ename='smith')
order by 1;

答案 1 :(得分:0)

可能是这个有用的

select e.ename,
       case when e.hiredate < khd.hiredate then 1 else 0 end king_header,
       case when e.hiredate > shd.hiredate then 1 else 0 end smith_juniour
from emp e, 
     (select hiredate from emp where ename='king') khd,  
     (select hiredate from emp where ename='smith') shd
where e.hiredate < khd.hiredate or e.hiredate > shd.hiredate