Oracle - 在union all子查询中排序

时间:2013-10-03 20:13:47

标签: sql oracle

我有一个查询,其中单个选择从表中提取最新结果。所以我有id desc的选择顺序,所以最新的是top,然后使用rownum来显示最高的数字。每个选择都是我想要最新结果的不同地方。

但是,我遇到的问题是订单不能在联合所有的select语句中使用。

select 'MUHC' as org, 
       aa, 
       messagetime 
  from buffer_messages 
 where aa = 'place1' 
   and rownum = 1 
 order by id desc
union all 
select 'MUHC' as org, 
       aa, 
       messagetime 
  from buffer_messages 
 where aa = 'place2' 
   and rownum = 1
 order by id desc;

每个选择必须包含订单,否则它不会提取最新版本。任何想法都是以不同的方式完全做到这一点,或者通过联合方式实现这一切,这些都可以得到我想要的结果?

3 个答案:

答案 0 :(得分:3)

试试这个

select 'MUHC' as org, 
   aa, 
   messagetime 
from buffer_messages bm
where aa = 'place1' 
and id= (Select max(id) from buffer_messages where aa = 'place1'  )
union all 
select 'MUHC' as org, 
   aa, 
   messagetime 
from buffer_messages 
where aa = 'place2' 
and id= (Select max(id) from buffer_messages where aa = 'place2'  )

答案 1 :(得分:0)

通过在where .. and rownum = 1子句之前放置order by条件,您将不会产生所需的结果,因为结果集将在where子句应用后排序,因此在结果集中只排序一行可以是查询返回的第一行。

此外,在order by子句之前放置union all子句在语义上是不正确的 - 您将需要一个包装器 select语句。

您可以按如下方式重写sql语句:

select *
  from ( select 'MUHC' as org
               , aa 
               , messagetime 
               , row_number() over(partition by aa
                                       order by id desc) as rn
           from buffer_messages 
        ) s
where s.rn = 1

这是第二种方法:

select max('MUHC')                                         as org
     , max(aa)                                             as aa
     , max(messagetime) keep (dense_rank last order by id) as messagetime 
 from buffer_messages
group by aa

答案 2 :(得分:0)

为了在所有子查询中使用ORION BY和UNION ALL,我们可以使用以下查询。

SELECT * FROM (
  SELECT 'MUHC' AS org, aa, messagetime
  FROM buffer_messages 
  WHERE aa = 'place1' AND rownum = 1
  ORDER BY id desc
)
UNION ALL
SELECT * FROM (
  SELECT 'MUHC' AS org, aa, messagetime
  FROM buffer_messages 
  WHERE aa = 'place2' AND rownum = 1
  ORDER BY id desc
)