How to sort the column via ORDER BY alphanumerically?

187 Views Asked by At

For my ABAP report, from database table field I want to retrieve the data of a field which has data type STRING, so it can be either alphanumeric or just numbers.

I tried this, but one little addition, all of the characters in a entry can be alphabets or numbers or any variations.

SELECT value
  FROM zyg_sort
  ORDER BY
    CASE WHEN value LIKE '[A-Z]%' THEN 1 ELSE 0 END DESCENDING,
    CAST( value AS NUMC( 3 ) ) DESCENDING,
    CAST( CASE WHEN value LIKE '[A-Z]%' THEN SUBSTRING( value, 2, 3 ) ELSE value END AS NUMC( 3 ) ) DESCENDING
  INTO TABLE @DATA(lt_0arphd). 

I am getting the data in this format

B998
A99
A999
A888
998
99
888

How to sort with Z-A like Excel?

B998
A999
A99
A888
998
888
99
1

There are 1 best solutions below

0
Suncatcher On

On my system I got the same results for ABAP and Excel

enter image description here

And without all your fluff of CASEs, just simply by

SELECT value FROM zyg_sort ORDER BY value DESCENDING.

ORDER order can be database-dependent, so can differ depends on the collation and locale of your DB, so your miles may vary.

If you are not satisified with the database sort order ABAP proposes you, you can always switch to internal table syntax that allows to refine how to sort, alphabetically or alphanumerically.

SORT itab ASCENDING AS TEXT

P.S. Sandra is right, your LIKE syntax is incorrect. Also I doubt that your column is string, or you provided us an invalid code. This code will not compile if the value is of STRING type, because STRING, LRAW, LCHR, RAWSTRING columns cannot be used in aggregate functions and in ORDER BY clause.