I am really stuck in UNION ALL join, below is senario

if i ran this query indivisually i get below result

1) Select salary as result from employee 
   where empno = '111628548' and seqno = 4   
   order by seqno Desc

result
------ 
$7000
$3000

2) Select descofemp as result from empdetail
   where empno = '111628548' and seqno = 4 
   order by seqno Desc

result
------
very good employee
good employee

above both result in string so column is same type. but when i join above two query with union all i get something like

With s1 as (Select salary from employee 
   where empno = '111628548' and seqno = 4   
   order by seqno Desc),

s2 as (Select descofemp from empdetail
   where empno = '111628548' and seqno = 4 
   order by seqno Desc
)
select * from s1                                                    
Union ALL                                                           
select * from s2  

Result
------
$3000
$7000
very good employee
good employee

You can see here the order of salary has been changed, i tried verious things but i am not able to understand why the order is changing in UNION ALL, does anybody know or faced this issue if yes could you please share some light on how to resolve it.

Thank you in advance.

Regards Mona

有帮助吗?

解决方案

Union does not guarantee the ordering of the results. You can, however, add in the ordering information and use that:

With s1 as (Select salary as col, row_number() over (order by seqno desc) as seqnum
   from employee 
   where empno = '111628548' and seqno = 4   
  ),  
s2 as (Select descofemp as col , row_number() over (order by seqno desc) as seqnum
   from empdetail
   where empno = '111628548' and seqno = 4 
)
select col
from (select * from s1                                                    
      Union ALL                                                           
      select * from s2
     ) t
order by seqnum
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top