Skip to content

Instantly share code, notes, and snippets.

@xtender
Last active April 18, 2025 21:48
Show Gist options
  • Save xtender/20940802ed8f5b4e702774fe2ae3ddcc to your computer and use it in GitHub Desktop.
Save xtender/20940802ed8f5b4e702774fe2ae3ddcc to your computer and use it in GitHub Desktop.
Sorting N non-unique digits (with repetitions) in Oracle SQL using RPAD, TRANSLATE, REGEXP_REPLACE, XMLQuery
with v(a) as (select to_char(n,'fm0000') from xmltable('9741,2415,9100,5532' columns n int path'.'))
select
a
,translate(
regexp_replace(
'0a0b0c0d1a1b1c1d2a2b2c2d3a3b3c3d4a4b4c4d5a5b5c5d6a6b6c6d7a7b7c7d8a8b8c8d9a9b9c9d'
,'('
||substr(a,1,1)||'a|'
||substr(a,2,1)||'b|'
||substr(a,3,1)||'c|'
||substr(a,4,1)||'d'
||')|\d[abcd]'
,'\1'
)
,'xabcd','x'
)
as sorted_1
,
rpad('0',4-length(replace(a,'0')),'0')
||rpad('1',4-length(replace(a,'1')),'1')
||rpad('2',4-length(replace(a,'2')),'2')
||rpad('3',4-length(replace(a,'3')),'3')
||rpad('4',4-length(replace(a,'4')),'4')
||rpad('5',4-length(replace(a,'5')),'5')
||rpad('6',4-length(replace(a,'6')),'6')
||rpad('7',4-length(replace(a,'7')),'7')
||rpad('8',4-length(replace(a,'8')),'8')
||rpad('9',4-length(replace(a,'9')),'9')
as sorted_2
,
translate(
translate(
'0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVW'
,'#'||translate(
'0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVW'
,'#'
||chr(48+0+(ascii(substr(a,1,1))-48)*4)
||chr(48+1+(ascii(substr(a,2,1))-48)*4)
||chr(48+2+(ascii(substr(a,3,1))-48)*4)
||chr(48+3+(ascii(substr(a,4,1))-48)*4)
,'#'
)
,'#'
)
,'0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVW'
,'0000111122223333444455556666777788889999'
)
as sorted_3
,xmlquery('string-join(for $cp in string-to-codepoints(.) order by $cp return codepoints-to-string(($cp)), "")'
passing a returning content).getstringval()
as sorted_4
from v
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment