如何在联合集运算符中的每个Oracle SQL查询中使用不同的order by子句

时间:2018-09-23 11:43:24

标签: sql oracle

我有两个表TEMP1和TEMP2,两个表中的列数相同。

  • Temp1- acct_no varchar2(20),序号,金额编号
  • Temp2-acct_no varchar2(20),序列号,金额号
例如,

来自temp1的数据将是这样

temp1

acct_no seq amount
200001  1   100
200001  2   50
200001  3   120
200001  4   40

temp2

acct_no seq amount
200001  1001    100
200001  1002    200
200001  1003    80
200001  1004    90

现在,我的要求是根据acct_no从temp1和temp2中获取数据,数据应如下所示。我希望首先通过使用seq降序从temp1中获取数据,然后再通过使用seq降序从temp2中获取数据。尝试了联合运算符,但将排序应用于最终输出。

seq amount
4   40
3   120
2   50
1   100
1004    90
1003    80
1002    200
1001    100

2 个答案:

答案 0 :(得分:1)

这里有两种略有不同的方法。第一种将ORDER BY依次应用于每个表,对结果排序后的结果集进行UNION组合:

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;

dbfiddle here

答案 1 :(得分:0)

您应该在整个结果集上使用明确的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;