多列中的 ORDER BY 排序冲突

ORDER BY in multiple column with sorting conflict

我有以下查询:

SELECT * FROM
    ( select 'All' as display,'-10' as key from dual
    UNION
    select distinct COUNTRY_NAME display, COUNTRY_CODE key 
    from COUNTRY 
    where COUNTRY_CODE<>'NUL' 
    order by key
     );

它显示如下输出:

预期输出:

基本上,国家名称需要按字母顺序排列,'All' 是第一个记录。但是,这两列数据似乎相互之间存在一些冲突,以便进行相应的整理。

"the country name need to be in alphabetically order with 'All' be the first record"

您的查询仅按 key 排序,因此 ORDER BY 不会产生您想要的顺序。为了保证您想要的顺序,您需要在外部查询上放置一个 ORDER BY 子句,然后按 key 然后 display 排序,如下所示:

SELECT * FROM
    ( select 'All' as display,'-10' as key from dual
      UNION 
      select COUNTRY_NAME display, COUNTRY_CODE key 
      from COUNTRY 
      where COUNTRY_CODE<>'NUL'
    )
 order by decode(key, '-10', 1, 99), display;

顺便说一下,您不需要 DISTINCT: UNION 会为您完成。