如何在union集合运算符中的每个oracle SQL查询中使用不同的order by子句
我有两个表TEMP1和TEMP2,两个表中的列数相同 Temp1-账号varchar220,序号,金额编号 Temp2-账号varchar220,序号,金额编号 比如说,, 来自temp1的数据如下 temp1如何在union集合运算符中的每个oracle SQL查询中使用不同的order by子句,sql,oracle,Sql,Oracle,我有两个表TEMP1和TEMP2,两个表中的列数相同 Temp1-账号varchar220,序号,金额编号 Temp2-账号varchar220,序号,金额编号 比如说,, 来自temp1的数据如下 temp1 acct_no seq amount 200001 1 100 200001 2 50 200001 3 120 200001 4 40 临时2 acct_no seq amount 200001 1001 100 200001 1002 200
acct_no seq amount
200001 1 100
200001 2 50
200001 3 120
200001 4 40
临时2
acct_no seq amount
200001 1001 100
200001 1002 200
200001 1003 80
200001 1004 90
现在我的要求是根据账号从temp1和temp2获取数据,数据如下所示。我希望首先使用order by seq降序从temp1获取数据,然后使用order by seq降序从temp2获取数据。已尝试使用联合运算符,但对最终输出应用了排序
seq amount
4 40
3 120
2 50
1 100
1004 90
1003 80
1002 200
1001 100
您应该在整个结果集上使用显式的order by。因此,使用union all将数据组合在一起,选择所需的列,然后使用适当的排序逻辑:
select seq, amount
from ((select t1.*, 1 as ord
from temp1 t1
) union all
(select t2.*, 2 as ord
from temp2 t2
)
) t
order by ord,
(case when ord = 1 then seq end) desc,
(case when ord = 2 then seq end) asc;
这里有两种稍微不同的方法。第一种方法依次将ORDER BY应用于每个表,并将结果排序结果集合并在一起:
select seq, amount
from (select *
from temp1
order by seq desc)
union all
select seq, amount
from (select *
from temp2
order by seq desc);
第二种方法是向结果集中添加一个表标识符,然后按表标识符和SEQ排序,以便根据需要对输出结果排序:
select seq, amount
from (select t1.*, 1 as table_index
from temp1 t1
union all
select t2.*, 2 as table_index
from temp2 t2)
order by table_index asc,
seq desc;
我想你只需要一组括号。