1

I have a query where the individual selects are pulling the most recent result from the table. So I'm having the select order by id desc, so the most recent is top, then using a rownum to just show the top number. Each select is a different place that I want the most recent result.

However, the issue I'm running into is the order by can't be used in a select statement for the union all.

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;

The each select has to have the order by, else it won't pull the most recent version. Any idea's of a different way to do this entirely, or a way to do this with the union all that would get me the desired result?

4

3 回答 3

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'  )
于 2013-10-03T20:21:16.920 回答
0

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

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

你可以重写你的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
于 2013-10-03T20:28:41.250 回答
0

对于在所有子查询中使用 ORDER 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
)
于 2018-01-19T05:38:00.930 回答