Varchar2用'_'表示的Oracle SQL顺序

时间:2019-08-22 10:12:14

标签: sql oracle sql-order-by

我有一个带有varchar2列的表。按该列排序并没有给我预期的结果:

with test (col) as
  (select '_83_' from dual union all
   select '_81_' from dual union all
   select '4___' from dual union all
   select '____' from dual
  )
select * from test
order by col desc;

返回:

Col 
1. '_83_'
2. '_81_'
3. '4___'
4. '____'

我确实期望:

Col 
1. '4___'
2. '_83_'
3. '_81_'
4. '____'

您能解释一下,并帮助我通过声明使'4___'到我的订单开始吗?

使用Littlefoots编辑语句以进行预生产...

编辑我正在使用Oracle 12c

编辑NLS_Sort设置为德语。这就是问题所在。

4 个答案:

答案 0 :(得分:3)

在我的本地数据库中,NLS_SORT设置为BINARY,因此它是不可复制的。

WITH TEMO AS 
(
SELECT '_83_' AS X FROM DUAL UNION ALL
SELECT '_81_' AS X FROM DUAL UNION ALL
SELECT '4___' AS X FROM DUAL UNION ALL
SELECT '____' AS X FROM DUAL
)
SELECT * FROM TEMO ORDER BY X DESC;

X   
----
____
_83_
_81_
4___

但是,在将NLS_SORTBINARY更改为GERMAN之后,问题再次出现。

ALTER SESSION SET NLS_SORT=GERMAN;

WITH TEMO AS 
(
SELECT '_83_' AS X FROM DUAL UNION ALL
SELECT '_81_' AS X FROM DUAL UNION ALL
SELECT '4___' AS X FROM DUAL UNION ALL
SELECT '____' AS X FROM DUAL
)
SELECT * FROM TEMO ORDER BY X DESC;

X   
----
_83_
_81_
4___
____

您可以使用下表检查NLS值:

NLS_SESSION_PARAMETERS
NLS_DATABASE_PARAMETERS

因此结论是NLS_SORT参数必须进行相应设置,因为并非每个人都希望使用技术进行排序。

NLS_SORT的默认值来自NLS_LANGUAGE

有关oracle documents的更多信息,请参阅NLS_SORT。

解决方案是根据需要更改NLS_SORT

干杯!

答案 1 :(得分:0)

我不明白这个问题。是的,发表评论会更合适,但我无法发布此内容:

SQL> with test (col) as
  2    (select '_83_' from dual union all
  3     select '_81_' from dual union all
  4     select '4___' from dual union all
  5     select '____' from dual
  6    )
  7  select * from test
  8  order by col;

COL
----
____
4___
_81_
_83_

SQL>

如您所见,我的结果与您的结果不同,即我无法复制您所说的话。您能再解释一次吗?

答案 2 :(得分:0)

使用Oracle 11g R2:

Select Column1 From (
    SELECT CAST( '_83_' AS varchar2(4) ) AS Column1 FROM dual
    union all
    SELECT CAST( '_81_' AS varchar2(4) ) AS Column1 FROM dual
    union all
    SELECT CAST( '4___' AS varchar2(4) ) AS Column1 FROM dual
    union all
    SELECT CAST( '____' AS varchar2(4) ) AS Column1 FROM dual
) A order by Column1  desc

输出:

____
_83_
_81_
4___

答案 3 :(得分:0)

我个人会推荐Tejash的答案,但您也可以使用以下内容来捏造它:

SELECT * FROM table ORDER BY TRANSLATE(col, '_', 'z') desc;