如何通过Oracle中两个查询的并集结果进行排序?

时间:2016-03-08 16:25:57

标签: sql oracle union sql-order-by

我有以下Oracle SQL可以正常工作,但第二个查询的结果在第一行而不是第二行返回。

如何在输出中维护序列,以便第一行查询结果显示在第一行,第二行显示在第二行,依此类推。

Oracle SQL

select
  sum(a.transaction_amount) as transaction_amount,
  'Last 30 Days Debit Volume (Current Year)' as sales_volume
from
  payment_transaction a,
  payment_settlement b
where
  a.transaction_status = 'S'
  and b.settlement_type = 'D'
  and trunc(b.transaction_date) > sysdate - 30
  and a.payment_transaction_id = b.payment_transaction_id

union

select
  sum(a.transaction_amount) as transaction_amount,
  'Last 30 Days Credit Volume (Current Year)' as sales_volume
from
  payment_transaction a,
  payment_settlement b
where
  a.transaction_status = 'S'
  and b.settlement_type = 'C'
  and trunc(b.transaction_date) > sysdate - 30
  and a.payment_transaction_id = b.payment_transaction_id

当前输出

TRANSACTION_AMOUNT       SALES_VOLUME
6272                     Last 30 Days Credit Volume (Current Year)
10719                    Last 30 Days Debit Volume (Current Year)

预期输出

TRANSACTION_AMOUNT       SALES_VOLUME
10719                    Last 30 Days Debit Volume (Current Year)
6272                     Last 30 Days Credit Volume (Current Year)

1 个答案:

答案 0 :(得分:4)

只需添加一个虚拟列进行排序

 SELECT <yourfields>
 FROM (
      SELECT 1 as dummy, <yourfields>
      FROM Query1
      UNION
      SELECT 2 as dummy, <yourfields>
      FROM Query2
     ) T
ORDER BY dummy