交换2个表的列值

时间:2018-06-06 17:54:56

标签: sql oracle sql-order-by

您好我有2张牌tab1tab2。我想将id的{​​{1}}列替换为tab1的{​​{1}}列。我可以在单id次查询中执行此操作吗?

输入:

tab2

输出应为

select

由于  Onkar

1 个答案:

答案 0 :(得分:1)

您确定Tab2的最后一行是102, 'ZZ'还是103, 'ZZ'(即id是不同且有序的)。

如果是103, 'ZZ',则以下查询有效:

select decode(sign(max(ascii(name))-77),-1, min(id), max(id)) id, name
  from
( 
select t1.id, t1.dr, t2.name from
(
  select id, dense_rank() over (order by id) dr from Tab1
  union all
  select id, dense_rank() over (order by id) dr from Tab2
) t1
 join
(
  select name, dense_rank() over (order by id) dr from Tab1
  union all
  select name, dense_rank() over (order by id) dr from Tab2
) t2 on ( t1.dr = t2.dr )
)
group by name;

SQL Fiddle Demo