【问题标题】:Oracle - order by in subquery of union allOracle - 在 union all 的子查询中排序
【发布时间】:2013-10-03 20:13:47
【问题描述】:

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

但是,我遇到的问题是 order by 不能在 union all 的 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;

每个选择都必须按顺序排列,否则它不会提取最新版本。有什么不同的方法可以完全做到这一点,或者有一种方法可以通过联合来做到这一点,这一切都会让我得到想要的结果?

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    试试这个

    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'  )
    

    【讨论】:

      【解决方案2】:

      通过将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
      

      【讨论】:

        【解决方案3】:

        为了在所有子查询中使用 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
        )
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-01-07
          • 1970-01-01
          • 2014-08-09
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多