Query to sort a column containing alphanumeric values

Hi,
I have a table whose column contains ALPHANUMERIC values. The column is of type VARCHAR(1).
I tried many queries (using UNION) to fetch records in Alphabets first and Numbers as last
I.e. A-Z should come first and then 0-9 values.
Please do the needful
Regards,
Mradul

I.e. A-Z should come first and then 0-9 values.Edit: Whoops, I forgot the ascii values for numbers were lower.
WITH t AS
(SELECT '0' c FROM DUAL
  UNION
SELECT '9' c FROM DUAL
  UNION
SELECT 'A' c FROM DUAL
  UNION
SELECT 'B' c FROM DUAL
SELECT c
  FROM t
ORDER BY TRANSLATE( UPPER(c)
                   , 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
                   , 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
     , TRANSLATE( UPPER(c)
                , '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
                , '0123456789'
C
A
B
0
9Message was edited by:
vg

Similar Messages

  • When sorting a column of alphanumerical, how do I get them to stay sorted?  When I go to the next column, the first column mixes up.

    How do I get a column of alphanumerical to stay sorted?  When I go to the next column, my first column gets mixed up.

    For my purpose, I'll have to go back to Excel.
    What is your purpose?  Note that Numbers 3.0 does not have a multicolumn sort interface the way you have in Excel (or Numbers 2.3). But it is generally easy to accomplish what you need to do.
    Say you have a column A on which you want an alphanumerical sort and within that you want to sort by B (the equivalent of Excel's "Sort by" A "Then by" B).
    First do a single column sort by B. Then do a single column sort by A.
    SG

  • Set a flag if certain columns contain a value

    I have a table with multiple different columns. Each of these fields can contain 1 or 0. So how would I write a statement that sets a "flag" if each of these columns contain a 1. Again, I only want the field to be set if
    each column in the row contains a 1. I know I can use "nested If statements" but I was wondering if there is a cleaner, more organized way.
    Thanks.

    >> I have a table with multiple different columns. Each of these fields [sic] can contain 1 or 0. So how would I write a statement that sets a "flag" if each of these columns contain a 1. <<
    You missed a basic concept; columns are not fields. This is fundamental. Then you do not know that we never use flags in SQL. That was assembly language, not SQL. Please read:
    https://www.simple-talk.com/sql/t-sql-programming/bit-of-a-problem/
    >> Again, I only want the field [sic] to be set if each column in the row contains a 1. I know I can use "nested If statements" but I was wondering if there is a cleaner, more organized way. <<
    SELECT
     CASE (c1+ c2+ c3+ ..+ cn)
      WHEN <<n>>  THEN 'All Bit flags on!'
      WHEN 0 THEN 'No Bit flags on!'
      ELSE 'Some Bit flags on!'
    END AS assembly_flg
    FROM Foobar;
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • How to sort alphanumeric values in datagrid numerically

    Hi all,
    I have a datagrid column which contains AlphaNumeric values.Is there a way i can sort these values in a numerical order
    eg:
    having d1,d11,12,13,d2,d3,d4
    d2 should come after d1..
    order should be d1,d2,d3,d4,d11,d12,d13
    Please help me out..if any have any idea..giving below thw code which is sorting as string
    protected function ColumnSortCompare( obj1:Object, obj2:Object ):int
            if ( !obj1 && !obj2 )
                return 0;
            if ( !obj1 )
                return 1;
            if ( !obj2 )
                return -1;
            var obj1Data:String = ComplexColumnData( obj1 ).toString();
            var obj2Data:String = ComplexColumnData( obj2 ).toString();
            if ( obj1Data < obj2Data )
                return -1;
            if ( obj1Data > obj2Data )
                return 1;
            return 0;
    Thanx in advance
    Rajesh

    Hi,
    Thanks for the reply. Please dont mind if the question is simple,as I am new to flex.
    While I am using
    return ObjectUtil.stringCompare(obj1[fieldName], obj2[fieldName]);
    it is throwing error as, undefined property fieldName.
    I am calling as this
    <mx:DataGridColumn headerText=""
                               editable="false"
                               sortCompareFunction="ColumnSortCompare"
                               textAlign="left"
                               dataField="{PORT_NAME}"
                               width="150"/>
    How I can resolve this.Please guide me.
    Thanks,
    Raj

  • Error changing data type to date in column containing blanks

    I am pulling data from an OLAP cube into PowerPivot. My data set contains several date columns wich are formatted as YYYY-MM-DD string values. After successfully importing the data, I am trying to set the data type of these columns to date.
    Apparently, when the column contains blank values, the conversion fails:
    The following system error occurred:  Type mismatch. Datatype conversion failed for [Table: 'SO fact table', Column: 'Shipping Date LastDateDate', Value: ''].
    When the column contains no blanks, the conversion succeeds.
    Would anyone have an idea for working around this issue ?
    Is there some MDX magic that I could use in my query in order to cast blank dates to something that PowerPivot would accept to convert, or to make the conversion to the date format right at the source ? 

    Hello,
    I did a quick test with data from Excel sheet formatted as text containing ISO date values with one blank value, in Power Pivot I then changed it to type "Date" and it works without an issue; so it must have an other reason:
    You can try to use the
    DAX function "DateValue" to convert the values
    Olaf Helper
    [ Blog] [ Xing] [ MVP]

  • Functionality to dynamically sort tableview columns

    Has anybody successfully tried sorting columns of a tableview component by clicking on its header? I need to sort a column containing dates in mm/dd/yyyy format. Please share your hints or code. BR, Maulin

    Hi,
    Here is the code, no support included :-):
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.Vector;
    import com.sapportals.htmlb.table.DefaultTableViewModel;
    public class SortTableModel extends DefaultTableViewModel implements Comparator {
         protected int currCol;
         protected Vector ascendCol; // this vector stores the state (ascending or descending) of each column
         protected Integer one = new Integer(1);
         protected Integer minusOne = new Integer(-1);
         public SortTableModel() {
              super();
              ascendCol = new Vector();
         public SortTableModel(Vector vec) {
              super(vec);
              ascendCol = new Vector();
         public SortTableModel(Vector vec, Vector vec2, int numberOfColumns) {
              super(vec, vec2);
              ascendCol = new Vector();
              setSortOrder(numberOfColumns);
    This method is the implementation of the Comparator interface.
    It is used for sorting the rows
         public int compare(Object v1, Object v2) {
              // the comparison is between 2 vectors, each representing a row
              // the comparison is done between 2 objects from the different rows that are in the column that is being sorted
              int ascending = ((Integer)ascendCol.get(currCol)).intValue();
              if (v1 == null && v2 == null) {
                   return 0;
              } else if (v2 == null) { // Define null less than everything.
                   return 1 * ascending;
              } else if (v1 == null) {
                   return -1 * ascending;
              Object o1 = ((Vector)v1).get(currCol);
              Object o2 = ((Vector)v2).get(currCol);
              // If both values are null, return 0.
              if (o1 == null && o2 == null) {
                   return 0;
              } else if (o2 == null) { // Define null less than everything.
                   return 1 * ascending;
              } else if (o1 == null) {
                   return -1 * ascending;
              if (o1 instanceof Number && o2 instanceof Number) {
                   Number n1 = (Number)o1;
                   double d1 = n1.doubleValue();
                   Number n2 = (Number)o2;
                   double d2 = n2.doubleValue();
                   if (d1 == d2) {
                        return 0;
                   } else if (d1 > d2) {
                        return 1 * ascending;
                   } else {
                        return -1 * ascending;
              } else if (o1 instanceof Boolean && o2 instanceof Boolean) {
                   Boolean bool1 = (Boolean)o1;
                   boolean b1 = bool1.booleanValue();
                   Boolean bool2 = (Boolean)o2;
                   boolean b2 = bool2.booleanValue();
                   if (b1 == b2) {
                        return 0;
                   } else if (b1) {
                        return 1 * ascending;
                   } else {
                        return -1 * ascending;
              } else {
                   // default case
                   if (o1 instanceof Comparable && o2 instanceof Comparable) {
                        Comparable c1 = (Comparable)o1;
                        Comparable c2 = (Comparable)o2; // superflous cast, no need for it!
                        try {
                             return c1.compareTo(c2) * ascending;
                        } catch (ClassCastException cce) {
                             // forget it... we'll deal with them like 2 normal objects below.
                   String s1 = o1.toString();
                   String s2 = o2.toString();
                   return s1.compareTo(s2) * ascending;
    This method sorts the rows using Java's Collections class.
    After sorting, it changes the state of the column -
    if the column was ascending, its new state is descending, and vice versa.
         public void sort() {
              Collections.sort(dataVector, this);
              Integer val = (Integer)ascendCol.get(currCol);
              ascendCol.remove(currCol);
              if (val.equals(one)) // change the state of the column
                   ascendCol.add(currCol, minusOne);
              else
                   ascendCol.add(currCol, one);
         public void sortByColumn(int column) {
              this.currCol = column;
              sort();
         public void setSortOrder(int numberOfColumns) {
              for (int i = 0; i < numberOfColumns; i++) {
                   ascendCol.add(one);

  • How to get rows where a varchar column contain pure numeric value

    hi,
    i have to make a query from a table that return only the rows where the occurrences of a string column contain a pure numeric value
    for example my table MYTABLE have the column COL1 varchar2(100)
    with values
    row 1 : '100'
    row 2 : '101 dalmatiens'
    row 3 : '102'
    row 4 : 'anything'
    i want to get only the rows 1 and 3 which are pure integer so i can sort and compare them like number.
    thanks

    SQL> with rt as   
      2  (select '100' str from dual union all 
      3  select '101 dalmatiens' from dual union all 
      4  select '102' from dual union all
      5  select '103 #$&''() 456' from dual union all
      6  select 'anything' from dual)
      7  /* End of sample data (rt) */
      8  select str
      9         ,trim(translate(str,'1234567890'||str,'1234567890')) num
    10  from rt
    11  where trim(translate(str,'1234567890'||str,'1234567890')) is not null;
    STR            NUM
    100            100
    101 dalmatiens 101
    102            102
    103 #$&'() 456 103456
    -- Oooooops, I misread and now have corrected it
    SQL> with rt as   
      2  (select '100' str from dual union all 
      3  select '101 dalmatiens' from dual union all 
      4  select '102' from dual union all
      5  select '103 #$&''() 456' from dual union all
      6  select 'anything' from dual)
      7  /* End of sample data (rt) */
      8  select str
      9         ,trim(translate(str,'1234567890'||str,'1234567890')) num
    10  from rt
    11  where trim(translate(str,'1234567890'||str,'1234567890')) = str;
    STR            NUM
    100            100
    102            102Message was edited by:
    ushitaki

  • Sorting of columns in report with values from lookup table (LOV)

    Hi,
    I have a report where I looku the values using a number of LOVs. I'd like to enable sorting on those columns in the report whihc works BUT the report get's sorted on the numric looku pvalue instead of the description for example COUNTRY_ID instead of COUNTRY_DESC.
    I have played around with the function APEX_ITEM.ITEM_TET_FROM_LOV in my SQL query:
    select ID, NAME,
    APEX_ITEM.TEXT_FROM_LOV(COUNTRY_ID, 'COUNTRY_LOOKUP') COUNTRY,
    from VAR
    But I get the following error:
    report error:
    ORA-06550: line 1, column 13:
    PLS-00103: Encountered the symbol "COLLECT" when expecting one of the following:
    := . ( @ % ;
    ORA-06550: line 1, column 82:
    PLS-00103: Encountered the symbol ";" when expecting one of the following:
    . ( , % from
    So I am thinking that I am doing something very wrong? Is there another way to accomplish this?
    Andy

    you need to use htmldb_item.text_from_lov in your query.
    this will then deocde the key value to the description within the query itself and therefore allow you to do your sorting.

  • Sorting a column does not result in distinct values on Dashboard prompts

    Hi,
    We have a period column, the records of which are 'JAN-02' , "FEB-02"...."DEC-09". We need sort this column in descending order in Dashboard Prompts. We have another column "Date", which has been used to sort the period column. To achieve this in descending order, we have converted Show Results from “All Values” to “SQL Results” in dashboard prmpts, then entered the below sql.
    SELECT "CODE COMBINATIONS"."LINE AC PERIOD" FROM INVOICE_PAYMENTS
    order by "CODE COMBINATIONS"."LINE AC DATE" desc
    The above sql resulted in non-distinct values as below. Using distinct in the above sql throws syntax error.
    Period
    JAN-09
    JAN-09
    JAN-09
    FEB-09
    FEB-09
    How do we get distinct values and in descending order??
    Thanks and appreciate any ideas
    Surya

    Go to advanced tab and check "Use distinct clause" that will fire a distinct to the query.
    In the rpd month logical column , there is an option called sort order in the general properties and you need to specify the date column if you need to sort it based on the date column and in the Answers you can simply enable Descending sort order on the same column. That should take care of it
    Hope it helps
    Thanks
    Prash

  • Query contains double value - seems cache problem

    Hi experts,
    in a Query (integrated planning) based on an Aggregationlevel based on a Multicube.
    The Multicube contains an Realtime InfoProvider to store planning data and a normal InfoProvider to show actual values.
    The load of actual values to the InfoProvider can be executed several times a month via ProcessChain -
    it´s a full load so the data loaded before will be deleted during the month in order to save the new monthly dataload.
    In the Query there were double values displayed for actual data after several loads during the month -
    but in the acutal InfoProvider only a single value is stored!
    It seems to be a buffer problem, since a deletion of all system buffers solves the problem - but this is not the way to handle the problem in productive area.
    How can the problem be solved?
    Setting of Planbufferquery of acutal data InfoProvider to not using Cache doesn't help.
    Thank you!
    Angie

    Hi,
    there is no data stored in acutal cube and the query column is restricted to actual cube.
    And actual cube only contains the value once, but the query can display the double value.
    If all buffers are reset, the query shows correct value - but this is not the way to handle the problem.
    What changes need to be made?
    Is there a setting in query cache or planningbuffer query cache or some other setting that can fix the problem?
    Best regards,
    Angie

  • Return the rows of the table where a column contains a specific value first

    I want my query to return the rows of the table where a column contains a specific values first in a certain order, and then return the rest of the rows alphabetized.
    For Example:
    Country
    ALBANIA
    ARGENTINA
    AUSTRALIA
    CANADA
    USA
    Now i want USA and CANADA on top in that order and then other in alphabetized order.
    Edited by: 986155 on Feb 4, 2013 11:12 PM

    986155 wrote:
    If it is 2 then i can write a case... i want generalised one where may be around 5 or 6 mentioned should be in descending order at the top and remaining in ascending order there after.Computers tend not to work in 'generalized' ways... they require specifics.
    If you store your "top" countries in a table you can then simply do something like...
    SQL> ed
    Wrote file afiedt.buf
      1  with c as (select 'USA' country from dual union
      2             select 'Germany' from dual union
      3             select 'India' from dual union
      4             select 'Australia' from dual union
      5             select 'Japan' from dual union
      6             select 'Canada' from dual union
      7             select 'United Kingdom' from dual union
      8             select 'France' from dual union
      9             select 'Spain' from dual union
    10             select 'Italy' from dual
    11           )
    12      ,t as (-- top countries
    13             select 'USA' country from dual union
    14             select 'United Kingdom' from dual union
    15             select 'Canada' from dual
    16            )
    17  select c.country
    18  from   c left outer join t on (t.country = c.country)
    19* ORDER BY t.country, c.country
    SQL> /
    COUNTRY
    Canada
    USA
    United Kingdom
    Australia
    France
    Germany
    India
    Italy
    Japan
    Spain
    10 rows selected.

  • Check the column data contains alphanumeric data

    I want to retrieve the column data from the table if the column data contains alphanumeric data
    Ex: select column1 from table1 where column1 contains alphanumeric data.column1 is declared as varchar2.
    Is the any function defined to check for alphanumerics in sql query?
    Thanks!!

    Like this ?
    SQL>
    SQL>  WITH Sample_Data AS (SELECT '3874' col FROM DUAL UNION ALL
      2                        SELECT '74' col FROM DUAL UNION ALL
      3                        SELECT '123' col FROM DUAL UNION ALL
      4                        SELECT '22FRE' col FROM DUAL UNION ALL
      5                        SELECT 'ABCD' col FROM DUAL UNION ALL
      6                        SELECT 'AB33FRE' col FROM DUAL
      7                         )
      8   SELECT col from Sample_data
      9    WHERE REGEXP_LIKE(col,'[[:alpha:]]')
    10    AND REGEXP_INSTR(col,'[0-9]')>0;
    COL
    22FRE
    AB33FRE
    SQL>

  • Sorting based on a specific value in Columns

    Hi All,
    Crystal 2008 version I have. And we are connecting to BW queries as source.
    In a crosstab, I want to sort my row values based on a column value.
    For example, in rows I have an element with three values . In column I have only one element(month), with couple of month values. My requirement is to sort rows based on a specific month (Mar'09 for example).
    .....................Jan'09......Feb'09.....Mar'09
    ABC...............10.............323...........33....
    XYZ...............32..............33............11....
    FGH...............5................34.............55...
    But when I try to sort based on the Month, I can not select a specific value(mar'09). And it sorts based on the total value (sum of all months).
    How can I achieve this problem?
    Thanks
    Ozan

    For {Sort Value}, if you wanted to sort on the Jan column, then substitute the field name that your example shows as 10 in row ABC.  For {row value}, substitute the field name that is used in the first column (ABC in the example).
    In other words, take the value that you want to sort on, and put it in front of the value currently displaying as the row header.  Then, sort on the results.
    The purpose of the "000000000.00" is to make the length of the number, when converted to string, a consistent size.  This is needed (a) so you know how many characters to strip off when displaying the row value, and (b) so the records don't sort as 1, 12, 2, 234, 235423, 25, 3, ...
    HTH,
    Carl

  • Sql query slowness due to rank and columns with null values:

        
    Sql query slowness due to rank and columns with null values:
    I have the following table in database with around 10 millions records:
    Declaration:
    create table PropertyOwners (
    [Key] int not null primary key,
    PropertyKey int not null,    
    BoughtDate DateTime,    
    OwnerKey int null,    
    GroupKey int null   
    go
    [Key] is primary key and combination of PropertyKey, BoughtDate, OwnerKey and GroupKey is unique.
    With the following index:
    CREATE NONCLUSTERED INDEX [IX_PropertyOwners] ON [dbo].[PropertyOwners]    
    [PropertyKey] ASC,   
    [BoughtDate] DESC,   
    [OwnerKey] DESC,   
    [GroupKey] DESC   
    go
    Description of the case:
    For single BoughtDate one property can belong to multiple owners or single group, for single record there can either be OwnerKey or GroupKey but not both so one of them will be null for each record. I am trying to retrieve the data from the table using
    following query for the OwnerKey. If there are same property rows for owners and group at the same time than the rows having OwnerKey with be preferred, that is why I am using "OwnerKey desc" in Rank function.
    declare @ownerKey int = 40000   
    select PropertyKey, BoughtDate, OwnerKey, GroupKey   
    from (    
    select PropertyKey, BoughtDate, OwnerKey, GroupKey,       
    RANK() over (partition by PropertyKey order by BoughtDate desc, OwnerKey desc, GroupKey desc) as [Rank]   
    from PropertyOwners   
    ) as result   
    where result.[Rank]=1 and result.[OwnerKey]=@ownerKey
    It is taking 2-3 seconds to get the records which is too slow, similar time it is taking as I try to get the records using the GroupKey. But when I tried to get the records for the PropertyKey with the same query, it is executing in 10 milliseconds.
    May be the slowness is due to as OwnerKey/GroupKey in the table  can be null and sql server in unable to index it. I have also tried to use the Indexed view to pre ranked them but I can't use it in my query as Rank function is not supported in indexed
    view.
    Please note this table is updated once a day and using Sql Server 2008 R2. Any help will be greatly appreciated.

    create table #result (PropertyKey int not null, BoughtDate datetime, OwnerKey int null, GroupKey int null, [Rank] int not null)Create index idx ON #result(OwnerKey ,rnk)
    insert into #result(PropertyKey, BoughtDate, OwnerKey, GroupKey, [Rank])
    select PropertyKey, BoughtDate, OwnerKey, GroupKey,
    RANK() over (partition by PropertyKey order by BoughtDate desc, OwnerKey desc, GroupKey desc) as [Rank]
    from PropertyOwners
    go
    declare @ownerKey int = 1
    select PropertyKey, BoughtDate, OwnerKey, GroupKey
    from #result as result
    where result.[Rank]=1
    and result.[OwnerKey]=@ownerKey
    go
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • How to hide one column in Alv if it doesnt contain any value

    Hi,
      In alv Grid if one coulmn doesnt conatin any value.I doesnt want to display in ALV grid.Is dat possible. Plz help.

    Hello Anu
    When you prepare your fieldcatalog check the column of the output itab for its contents, e.g.:
    " Itab GT_FCAT contains fieldcatalog.
    " Itab GT_OUTTAB contains ALV list data.
    " Condition: column "MY_COLUMN" should contain at least single value > 0
      LOOP AT gt_outtab TRANSPORTING NO FIELDS
                     WHERE ( my_column > 0 ).
        EXIT.
      ENDLOOP.
      IF ( syst-subrc NE 0 ).  " Column "MY_COLUMN" contains no value > 0, then hide column
        READ TABLE gt_fcat INTO ls_fcat
                  WITH KEY fieldname = 'MY_COLUMN'.
        IF ( syst-subrc = 0 ).
          ls_fcat-no_out = 'X'.  " not displayed, but visible in layout
          ls_fcat-tech = 'X'.     " not displayed, not available in layout
          MODIFY GT_FCAT FROM ls_fcat INDEX syst-tabix.
        ENDIF.
      ENDIF.
    Regards
      Uwe

Maybe you are looking for