0

甲骨文 11g。WASHINGTON DC 不在我的 STATES 表中,我无权添加它,但它需要在结果集中。我还希望 DC 在排序顺序中首先出现。

STATES
STATE_ID  STATE_DESC
----------------------
 FL       FLORIDA
 HI       HAWAII
 WY       WYOMING
-----------------------------------------

select 'DC' state_id, 'WASHINGTON DC' state_desc from dual
union
select state_id, state_desc from states
order by 
case  state_id
when 'DC' then 'AAAA'
else state_desc
-------------------------

上面的查询产生以下错误消息:

 ORA-01785: ORDER BY item must be the number of a SELECT-list expression

期望的结果

 STATE_ID  STATE_DESC
 DC        WASHINGTON DC
 FL        FLORIDA
 HI        HAWAII
 WY        WYOMING
4

2 回答 2

2

你似乎只需要一个外部SELECT来应用它ORDER BY。就像是

SQL> ed
Wrote file afiedt.buf

  1  with states as (
  2    select 'FL' state_id, 'Florida' state_desc from dual union all
  3    select 'HI', 'Hawaii' from dual union all
  4    select 'WY', 'Wyoming' from dual
  5  )
  6  select state_id, state_desc
  7    from (select 'DC' state_id, 'Washington D.C.' state_desc
  8            from dual
  9          union all
 10          select state_id, state_desc
 11            from states)
 12   order by (case when state_id = 'DC'
 13                  then 'AAA'
 14                  else state_desc
 15*             end)
SQL> /

ST STATE_DESC
-- ---------------
DC Washington D.C.
FL Florida
HI Hawaii
WY Wyoming

虽然它可能无关紧要,因为您的STATES表可能只有 50 行左右,但是执行 aUNION ALL而不是 aUNION通常会更有效,因为它不需要 Oracle 检查和消除重复行。

于 2012-04-25T15:11:45.663 回答
0

我没有 Oracle 来检查优化器,但是我倾向于采用这样的方法

SELECT  State_ID, State_Desc
FROM    (   SELECT 1 AS SortOrder, State_ID, State_Desc
            FROM States
            UNION ALL
            SELECT 0, 'DC', 'WASHINGTON DC' 
            FROM Dual
        ) 
ORDER BY SortOrder, State_ID

更改排序顺序,而不是使用 case 语句。在 SQL-Server-2008 中使用SortOrder列肯定更有效。

于 2012-04-25T15:49:26.117 回答