排序依据:ABC之前的特殊字符

时间:2018-04-12 08:34:25

标签: oracle oracle10g sql-order-by special-characters

我有这个sql:

SELECT -1 AS ID, '(None)' AS NAME
FROM TABLE_1 WHERE ID=1
UNION
SELECT ID, NAME
FROM TABLE_2
ORDER BY 2

Table data:
ID | NAME
1  | Direct
2  | Personal
3  | Etc

因此,如果我在Oracle 10中执行此sql,则返回以下内容:

Result:
ID | NAME
1  | Direct
3  | Etc
-1 | (None)
2  | Personal

如何将“(无)”排在最前面?

如果我使用

' (None) ' as Name

而不是

'(None)' as Name

它有效,因为(None)之前的空格,但这不是解决方案。

2 个答案:

答案 0 :(得分:1)

您可以添加虚拟列ORDER_COL,然后在该列

上订购
select ID, NAME from 
(
    SELECT -1 AS ID, '(None)' AS NAME, 1 as ORDER_COL FROM TABLE_1 WHERE ID=1
    UNION
    SELECT ID, NAME, 2 as ORDER_COL FROM TABLE_2
)
order by ORDER_COL, NAME; 

答案 1 :(得分:1)

试试这个。 NULLS LAST是Oracle中升序的默认值。为'(无)'制作NULLS FIRST。另外,使用UNION ALL作为UNION会删除重复项,但效率会降低。

SELECT *
FROM (
    SELECT -1 AS ID
        ,'(None)' AS NAME
    FROM TABLE_1
    WHERE ID = 1
       UNION ALL
    SELECT ID
        ,NAME
    FROM TABLE_2
    )
ORDER BY CASE 
        WHEN NAME = '(None)'
            THEN NULL
        ELSE NAME -- or id if you want
        END NULLS FIRST;