How to sort texts with '_' in Oracle exactly like EXCEL?

岁酱吖の 提交于 2021-01-29 17:48:58

问题


In Excel When I sort the texts in ascending order, results shows as below. Text with the underscore character precedes the others. And in Excel cell, when I type in ="_" < "A", then "True" shows as expected.

C10_
C10A
C20_
C20A

But, In Oracle, when I sort in ascending order, results shows as below. (I guess, Oracle treats '_' < 'A' False)

C10A
C10_
C20A
C20_

How can I make Oracle sort the list exactly as Excel does? I have changed ASC to DESC, but the result was not what I expect.

My sorting code is as below,

WITH DATAA AS (
SELECT *
FROM
(
SELECT 'C10_'rr  FROM DUAL
UNION
SELECT 'C10A' rr FROM DUAL
UNION
SELECT 'C20_' rr FROM DUAL
UNION
SELECT 'C20A' rr FROM DUAL
)
)
SELECT * 
FROM DATAA 
ORDER BY rr ASC;

回答1:


You can achieve this by altering the sorting method using NLS_SORT as following:

According to ORACLE Documentation:

NLS_SORT specifies the type of sort for character data. It overrides the default value that is derived from NLS_LANGUAGE.

NLS_SORT contains either of the following values:

NLS_SORT = BINARY | sort_name

BINARY specifies a binary sort. sort_name specifies a linguistic sort sequence.

Here is how you can achieve the result.

SQL> -- Your original query
SQL> --
SQL> WITH DATAA AS (
  2  SELECT *
  3  FROM
  4  (
  5  SELECT 'C10_'rr  FROM DUAL UNION
  6  SELECT 'C10A' rr FROM DUAL UNION
  7  SELECT 'C20_' rr FROM DUAL UNION
  8  SELECT 'C20A' rr FROM DUAL )
  9  )
 10  SELECT *
 11  FROM DATAA
 12  ORDER BY rr ASC;

RR
----
C10A
C10_
C20A
C20_

--

SQL> -- Now altering the sorting method
SQL> --
SQL> --
SQL> alter session set NLS_SORT = German;

Session altered.

SQL> --
SQL> --
SQL> -- Now see the result
SQL> --
SQL> --
SQL> WITH DATAA AS (
  2  SELECT *
  3  FROM
  4  (
  5  SELECT 'C10_'rr  FROM DUAL UNION
  6  SELECT 'C10A' rr FROM DUAL UNION
  7  SELECT 'C20_' rr FROM DUAL UNION
  8  SELECT 'C20A' rr FROM DUAL )
  9  )
 10  SELECT *
 11  FROM DATAA
 12  ORDER BY rr ASC;

RR
----
C10_
C10A
C20_
C20A

SQL>

Cheers!!



来源:https://stackoverflow.com/questions/57886461/how-to-sort-texts-with-in-oracle-exactly-like-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!