问题
I have an Oracle 10g DB and have a VARCHAR2 (2000 Character) column lets name it TEST which can contain numbers in front for example:
test
1test
3test
When I call "... order by TEST asc" or simply "... order by TEST"
I get the results ordered like
test
1test
3test
But I would like to get the results ordered like this:
1test
3test
test
So the numbered inserts first, is there a method to achieve this?
回答1:
What is your NLS_SORT set to? (select sys_context('USERENV', 'NLS_SORT') from dual
). If it is BINARY
then the sort order is based on the numeric value of each character, so it's dependant on the database character set. If it's something else then you might want to override it.
You can change the sort order at database or session level by modifying that parameter, but you can also change it for a single query:
order by nlssort(test,'NLS_SORT=BINARY')
Depending on your character set you might need to experiment with different values instead of BINARY
. You can get a list of all the valid values with select value from v$nls_valid_values where parameter = 'SORT'
. But note the potential performance impacted mentioned in the NLS_SORT documentation.
The nlssort()
function is documented here.
回答2:
You could replace the previous answers substr test with a regexp
order by case when regexp_instr(test,'[0-9]+') = 1 then
to_number(regexp_substr(test,'[0-9]+'))
else
null
end nulls last, test
It should be something like that - you can tweak the regexp according to what you want.
回答3:
One way:
order by case when substr(test,1,1) between '0' and '9' then 1 else 2 end,
test
回答4:
Using substr is working fine.If we want numbers in ascending order and character in descending order.what is the workaround.
来源:https://stackoverflow.com/questions/5257867/10g-ordering-varchar-columns-when-containing-numbers-in-front