Comparator for multiple column sorting

Hi,
Wr have written a below query
select p.name, o.id, ol.name, pr.name from Person p , Order o , OrderLine ol, Product pr where...
order by p.key asc, o.key asc, ol.key desc, pr.key desc
This query is taking lot of time as it seems the ORDER BY is taking more time. Hence we thought of moving sorting in the java side.
Here whether I need to create 4 comparators
1) PersonComparator with p.key asc
2) OrderComparator with o.key asc
3) OrderLineComparator with ol.key desc
4) ProductComparator with pr.key desc
This query returns a list , hence we need to do some thing like this
Collections.sort(list, new PersonComparator())
Collections.sort(list, new OrderComparator())
Collections.sort(list, new OrderLineComparator())
Collections.sort(list, new ProductComparator())
Is there any other better way of handling this sorting as 2 fields needs asc and other 2 fields needs desc. Whether we need to create 4 comparators for each object?
Please clarify. If there is any alternative please specify that as well.
Thanks.

>
This query is taking lot of time as it seems the ORDER BY is taking more time
>
Not sure how you drew that conclusion. There is nothing in your post to support it. Oracle is very efficient at sorting.
More likely the joins and filters (which you didn't show) in your query are either not using existing indexes or the proper indexes don't exist.
Post the question in the SQL and PL/SQL forum and provide the following information
1, Read the FAQ at the top of the main forum page for how to post tuning requests - it will include the below info
2. The 4 digit Oracle version (post results of SELECT * FROM V$VERSION)
3. The full query
4. The DDL for the Person, Order and OrderLine tables
5. The DDL for the existing indexes on the table
6. The approximate number of records in each table
7. The expected number of records you expect in the result set
8. The execution plan for the query
A. Open a sql*plus session
B. set serveroutput on
C. set autotrace traceonly
D. SELECT P.NAME ... -- that is, execute the query
E. Copy and Paste the entire output of the result, including the execution plan
You (or your DBA) need to determine how much work is being done and where the time is being taken before deciding what solutions to consider. The phrase 'taking more time' doesn't mean anything unless you have something to compare it to. Ten seconds to return one record could be slow while ten minutes to return 1 million records could be fast.

Similar Messages

  • Multiple Column sort Pop Up not opening using af:PanelCollection

    Hi guys,
    I have a table in which i want to sort on the basis of Multiple Columns.For that I have used af:PanelCollection but when in menus my advance sort Pop Up is Not opening.I am using jdeveloper 11.1.1.6.
    <af:panelCollection id="pc1" styleClass="AFStretchWidth"
    partialTriggers="t1">
    <f:facet name="menus"/>
    <f:facet name="toolbar"/>
    <f:facet name="statusbar"/>
    <af:table value="#{bindings.xx_sw_vwVO.collectionModel}"
    var="row" rows="#{bindings.xx_sw_vwVO.rangeSize}"
    emptyText="#{bindings.xx_sw_vwVO.viewable ? 'No data to display.' : 'Access Denied.'}"
    fetchSize="#{bindings.xx_sw_vwVO.rangeSize}"
    rowBandingInterval="0"
    width="100%"
    selectionListener="#{bindings.xx_sw_vwVO.collectionModel.makeCurrent}"
    inlineStyle="height:350;"
    rowSelection="single" id="t1"
    partialTriggers="::cb1 ::sor1"
    contentDelivery="immediate" immediate="true"
    autoHeightRows="30" columnSelection="multiple">
    <af:clientListener method="sskuRowSelection" type="click"/>
         <af:serverListener type="sskuRowSelectEvent"
    method="#{DataworkbenchBN.sskurowselect}"/>
    <af:column sortProperty="SskuId" sortable="true"
    headerText="#{bindings.xx_sw_vwVO.hints.SskuId.label}"
    id="c33">
    <af:inputText value="#{row.bindings.SskuId.inputValue}"
    label="#{bindings.xx_sw_vwVO.hints.SskuId.label}"
    required="#{bindings.xx_sw_vwVO.hints.SskuId.mandatory}"
    columns="#{bindings.xx_sw_vwVO.hints.SskuId.displayWidth}"
    maximumLength="#{bindings.xx_sw_vwVO.hints.SskuId.precision}"
    shortDesc="#{bindings.xx_sw_vwVO.hints.SskuId.tooltip}"
    id="it17">
    <f:validator binding="#{row.bindings.SskuId.validator}"/>
    </af:inputText>
    </af:column>

    ADF -- panelCollection multiple column sort
    ~Abhijit

  • Setting different Tabel Cell SemanticColor for Multiple Columns of each row

    Hi,
    I have requirement of setting different colors to different columns for each row based on some condition in table data.
    The data to table is coming from model, hence table is mapped to model node and attributes.
    I have created Seperate Node CellColorNode with attribue CellClr1 and CellClr2 of type TextView Semantic Color.
    Set the calculated, read only attribute to True. Mapped table columns text view to the CellColorNode->CellClr1 and CellColorNode-->CellClr2 correspondingly.
    Now, my query is how do i set the colors to CellClr1 and CellClr2 attributes. As I need to set the color for multiple columns of each table row.
    Is it in method getColorCellCellClr generated? Any  Example Code?

    Its resolved by following below link
    http://scn.sap.com/thread/158286

  • Single heading for Multiple columns in ALV

    Hi Experts,
          I need to display a common column heading for multiple columns in my ALV Grid Display output. I am giving the sample output here.
    MATNR...WERKS..| Unrestricted Stock|....|Stock in transfer        |....|Stock in Quality|.
    ............................| CAT | SAP  | Differe| .. |  CAT   |  SAP  | Diff   | .. | CAT   |  SAP  | Diff  |
    As I shown above, for 3 columns CAT, SAP, and for Difference, I need to get "Unrestricted Stock" as column heading... and so on...
    Pl. suggest me on this.
    Thanks in Advance
    Ramakrishna

    Hello Ramki,
    NOT POSSIBLE IN ALV AT ALL :-((
    You have to use classical report using WRITE stmts for this.
    If your client does not want to lose ALV functionalities, then you can try something like.
    Unrestricted Stock-SAP | Unrestricted Stock-CRM | Unrestricted Stock-Diff. Stock ... and so on !!!
    BR,
    Suhas
    Edited by: Suhas Saha on Jan 21, 2009 3:00 PM

  • Multiple column sorting in JTable

    There is way to release multiple column sorting in JTable.
    ADF/SWing, Jdev 10.1.3

    I do not know that there is, but it would be really nice!
    regards,
    mario udina

  • Multiple column  sorting on JTable data

    if any body can please send an example code how multiple column sorting can be done on table data.
    condition:- one column should sort in ascending order another column in descending order.
    am completly out of ideas it's urgent any help is greatly appritiated
    Thank's in advance
    sri

    I think the crosspost is because the OP was advised to post it in the Swing forum instead (it would've been nice to see the original post closed as well, though). Anyway...
    Have you got your table sorting using one column? If so, how have you achieved that (eg, are you using Java 6)?
    All you're after is a stable sorting algorithm so that any elements that are the same in the new sorting scheme stay in the same position relative to each other. Then you can just sort by "Column B" then "Column A" to achieve multiple column sorting. I believe that Collections.sort is stable and therefore any sorting approach based on that should be easily modifiable to do what you want.
    Hope this helps.

  • Sorting a Collection with dynamic columns using a custom compare function for multiple columns

    I need help and ideas on how to sort a ListCollectionView.  My problem is complicated by 3 requirements-
         1. The column values contain HTML tags that needs to be removed before sorting (use custom compareFunction to strip HTML)
         2. The columns are dynamic, so dataField names are not known at compile time (need a single compareFunction for all columns)
         3. The data is used in an AdvancedDataGrid so multi-column sorting is required
    I have figured out how to solve any 2 of the 3 requirements.  However, I am having difficulties supporting all 3 requirements.
    Any help or ideas would be greatly appreciated.  Thanks.

    After playing with this some more I think I've figured out a solution.  This seems to work in initial testing.  Also, there is not a need to capture the current sort column in the headerRelease event which many offered solutions suggested.  Another benefit to this solution is that keyboard initiated sorting is handled also.  Whereas the headerRelease event is only triggered by a mouse click on the column header and special handling is required if the user uses the keyboard to access the column header.
    One point that I don't understand is how ascending/decending order is determined.  Behavior seems to be different between a single SortField versus multiple SortFields.  Notice how the compareResults are handled for the different situations.  Anyone out there know why???
     private function colSortCompareFunction(obj1:Object, obj2:Object, fields:Array = null):int{
         var compareResults:int = 0; 
         var newObj1:Object = new Object(); 
         var newObj2:Object = new Object();
          // should not be a condition that is met   
         if (_dataProviderDetails.sort.fields == null)     {
              var s:Sort = new Sort(); 
              var f:Function = s.compareFunction; 
              return f.call(null, obj1, obj2, fields);     }
         // when a single column is selected for sorting   
         else if (_dataProviderDetails.sort.fields.length == 1)     {
              var firstFld:SortField = _dataProviderDetails.sort.fields[0];
              newObj1[firstFld.name] = stripHTML(obj1[firstFld.name]as String);          newObj2[firstFld.name] = stripHTML(obj2[firstFld.name]
    as String);
              compareResults = ObjectUtil.compare(newObj1[firstFld.name], newObj2[firstFld.name]);
               return compareResults;     }
         // when multiple columns are selected for sorting   
         else       {
              for each (var fld:SortField in _dataProviderDetails.sort.fields)          {
                   newObj1[fld.name] = stripHTML(obj1[fld.name]
    as String);               newObj2[fld.name] = stripHTML(obj2[fld.name]
    as String);
                   compareResults = ObjectUtil.compare(newObj1[fld.name], newObj2[fld.name]);
                    if (compareResults != 0)               {
                        if (fld.descending)                    {
                             return compareResults * -1;                    }
                        else                      {
                             return compareResults;                    }
               return compareResults;     }
    Does anyone see any problems with this solution?
    NOTE:  stripHTML(String) is a simple function using regular expression to remove HTML tags.
    Thx

  • Multiple column sorting.

    How does one sort multiple columns( date, String, time etc...). I want to sort by date where two dates can be alike as well. I could use HashMap for that reason.
    Please help.
    Thanks in advance.

    Hi,
    A demo of the comparator class is given below. I've tried to put it into the table class.
    import java.util.*;
    import javax.swing.*;
    import java.awt.BorderLayout;
    import java.awt.event.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    class MultipleColumnSortTest
         MultipleColumnSortTest()
              JFrame frame = new JFrame("MultipleColumnSortTest");
              frame.setBounds(10,10,750,550);
              Vector fieldNames = new Vector();
              fieldNames.add("Dates");
              fieldNames.add("Strings");
              Vector dataVector = new Vector();
              for(int i = 0; i < 5; ++ i)
                   Vector row = new Vector();
                   row.add(new Date());
                   row.add("abc" + i%2);
                   dataVector.add(row);
              final SortableDataVector tableModel = new SortableDataVector(dataVector,fieldNames);
              int [] sortIndices = new int[2];
              sortIndices [0] = 0 ;
              sortIndices [1] = 1 ;
              tableModel.setSortPriority(sortIndices);
              JTable table = new JTable(tableModel);
              JScrollPane scrollpane = new JScrollPane(table);
              frame.getContentPane().add(scrollpane);
              JButton button = new JButton("Sort Data");
              frame.getContentPane().add(button,BorderLayout.SOUTH);
              button.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent event)
                        tableModel.setAscendingOrder(!tableModel.isAscendingOrder());
                        tableModel.sort();
              frame.setVisible(true);
         public static void main(String [] args)
              MultipleColumnSortTest appln = new MultipleColumnSortTest();
    class SortableDataVector extends DefaultTableModel implements Comparator
         private int [] indices;
         private boolean isAscendingOrder;
         public SortableDataVector(Vector dataVector, Vector fieldNames)
              super(dataVector,fieldNames);
              setAscendingOrder(true);
         public void setAscendingOrder(boolean b)
              isAscendingOrder = b;
         public boolean isAscendingOrder()
              return isAscendingOrder;
         public void setSortPriority(int [] indices)
              this.indices = indices;
         public int compare(Object o1,Object o2)
              int comparisonResult = compareAscending(o1,o2);
              if(!isAscendingOrder)
                   if(comparisonResult < 0)
                        comparisonResult = 1;
                   else if (comparisonResult > 0)
                        comparisonResult = -1;               
              return comparisonResult;
         private int compareAscending(Object o1, Object o2)
              int comparisonResult = 0;
              if((o1 == null)&&(o2 != null))
                   comparisonResult = -1;
              else if((o1 != null)&&(o2 == null))
                   comparisonResult = 1;
              else if((o1 != null)&&(o2 != null))
                   List firstRow = (List)o1;
                   List secondRow = (List)o2;
                   for(int i = 0; ((i < indices.length)&&(comparisonResult == 0)); ++i)
                        if(indices[i] < firstRow.size())
                             comparisonResult =
                                  DatatypeSensitiveComparator.compare(
                                       firstRow.get(indices),
                                       secondRow.get(indices[i]));
              return comparisonResult;
         public boolean equals(Object obj)
              if(obj == null)
                   return false;
              return this.equals(obj);
         public void sort()
              if((indices != null)&&(indices.length > 0))
                   Collections.sort(dataVector,this);
                   fireTableChanged(new TableModelEvent(this));
    class DatatypeSensitiveComparator
         public static int compare(Object firstValue, Object secondValue)
              int comparisonResult = 0;
              if((firstValue != null)&&(secondValue == null))
                   comparisonResult = 1;
              else if((firstValue == null)&&(secondValue != null))
                   comparisonResult = -1;
              else if((firstValue != null)&&(secondValue != null))
                   Class clazz = firstValue.getClass();
                   if(!clazz.equals(secondValue.getClass()))
                        throw new IllegalArgumentException("Class are not the same ->"
                             + clazz.getName() + ":" +
                             secondValue.getClass().getName());
                   if(clazz.equals(String.class))
                        comparisonResult = ((String)firstValue)
                             .compareTo(((String)secondValue));
                   else if(clazz.equals(Date.class))
                        comparisonResult = ((Date)firstValue)
                             .compareTo(((Date)secondValue));
              return comparisonResult;

  • NamedQuery problem- single argument compared to multiple columns

    Hello,
    I'm not sure if this issue is a bug or if I'm misinterpreting the API. I'm trying to execute a text search query against multiple columns in the same table via EJB 3.0, e.g.
    select object(o) from Location o where o.city LIKE :searchString OR o.county LIKE :searchString"So, a single text argument is compared to multiple fields- but I keep getting an exception that the number of supplied arguments (one) does not match the number of required arguments (one- even though it's ID is referenced twice). Is there a separate syntax for repeating arguments in EQL (EJB 3.0, JDeveloper 10.1.3)? Is it not supported?
    I get around the issue by just specifying a Query at runtime, but I'd prefer --if possible-- to create a NamedQuery instead.
    Any help would be appreciated. Take care.

    Should the EJBQL statement be
    select object(o) from Location o where o.city LIKE :?1 OR o.county LIKE :?2

  • Multiple Column Sorting in iTunes

    I have seen many conversations around the edges of this, but no answers.  I am curious if it is possible to configure a custom sort in iTunes involving multiple columns. 
    Here is what I would like to end up with - Artist; Sort Show (where I have stored the release date); Album; Disk Number; Track Number.  Seeing my albums in chronological order is the way I always sorted physical albums, I would like to store my virtual ones the same way.  iTunes allows me to use Album by Artist and then sort by Sort Show, but this then displays the tracks in alphabetic order by name! 
    Identifying multiple sort columns (as in Excel) would be ideal.  Thanks for any help you can provide.
    Dave

    It is a database internally, and there are some multivalued sorts, but as users we don't get to specify custom sort orders. Album by Artist is more properly Album by Album Artist and in pseudo-SQL it would go something like this.
    SELECT * FROM Selection ORDER BY SortAlbumArtist, SortAlbum, Disc# , Track#
    Where there is no SortAlbumArtist it is inferred from the first non-empty value of AlbumArtist, SortArtist or Artist.
    Where there is no SortAlbum it is inferred from Album.
    The Disc# & Track# sorts place empties last.
    Presumably the designers think they've included useful options and adding nested sorting features would be too complicated, but you can make suggestions via iTunes Feedback.
    tt2

  • Layout for multiple column

    Dear all,
    I have a layout setting that is supposed to have multiple columns. The first columns I have a fixed width in pixel (for example 120px), and the rest of the columns I want to set it in %. So, if the user resize its browser, the first column will stay 20px, while the rest will resize accordingly.
    What is the best way of doing this in JSC?
    thank you in advance

    1. In first, second, and third rows, I have a label
    and a text field. I want to left justify the label,
    and the textfield. So, using gridPanel with 2 columns
    will do the job.
    2. In the fourth, fifth, sixth row, I have 2 labels
    and 2 fields.In this order?
    I want to keep the left justify setting
    for the first label and textfield. If can't use the
    grid panel because the layout for each labels are not
    left justified with the same component in the first
    and second rows. Beside the width of each labels and
    textFields are not the same.That's why I'am not using the label attribute of TextField but separate Label components.
    Create a Grid Panel with 4 columns and drop into
    label1, textfield1, dummylabel11, dummylabel12
    label2, textfield2, dummylabel21, dummylabel22
    label3, textfield3, dummylabel31, dummylabel32
    label4, textfield4, label5, textfield5
    label6, textfield6, label7, textfield7
    label8, textfield8, label9, textfield9
    Create CSS classes for example as follows:
    *.gridlabel {...}
    *.griddata {...}
    Set the columnClasses attribute of the GridPanel to "gridlabel, griddata, gridlabel, griddata".
    To arrange more than one components in one cell of the GridPanel wrap them in a LayoutPanel without attributes.

  • JDBC, SQL-SELECT: Aliases for multiple columns?

    Folks;
    using SQL, JDBC with MaxDB 7.6, I am used to doing something like
    SELECT A AS FOO_A, B AS FOO_B, C AS BAR_C FROM FOO, BAR WHERE ...
    in order to make table columns have names sometimes more "meaningful" than in the actual database scheme. In a give environment, I will have to do a
    SELECT * FROM FOO,BAR WHERE ...
    with the difficulty that FOO and BAR contain columns of the same name, yet they both contain too many columns to actually enumerate/alias each one of them manually. Playing around trying something like
    SELECT FOO.* AS FOO_*, BAR.* AS BAR_* FROM FOO,BAR WHERE ...
    of course didn't work, and browsing the web I found there is no "standard SQL" way of doing something like this. Using
    java.sql.ResultSet
    provides a
    getMetaData()
    method which allows for determining the "table name" for a given column in the fetched result set, but unfortunately, the outcome returned by this method always seems to be empty. So to ask:
    - Is there any way in MaxDB-SQL to allow for "aliasing multiple columns"?
    - Alternatively, is there a way to make an SQL query joining multiple tables in MaxDB issued through JDBC generally return table columns in a <tablename>.<columnname> rather than just <columnname> style?
    Thanks a bunch in advance, best regards.
    Kristian

    HI Kristian,
    afaik the resultset.getMetaData() method should provide a MetaData-object that in turn implements methods like getColumnCount() or getColumnName() etc...
    Can you provide a piece of code to demonstrate that this is not working?
    I just tested DB Studio and Squirrel SQL (both use JDBC to connect to the database) and both are able to correctly figure out the structure of the result set for a query like yours.
    Anyhow, the whole requirement is not supposed to be supported.
    In fact, it's already a kind of 'glitch' that results with non-unique columnnames are actually produced, since relational theory forbids such results.
    That's also the reason for why you cannot further work with such a resultset (e.g. use it in a join).
    Therefore, no workaround in place here.
    If you´re going to have a query like this rather often, you may think about using views and define the aliases there only once.
    And besides all this, if you've got many duplicate column names it might also be a unlucky data design.
    best regards,
    Lars

  • 3.1 Multiple column sorts.

    I have a report which I would like to have multiple columns that default in an ascending sort sequence order.
    Example:
    Column 1 will be sort sequence 2.
    Column 2 will be sort sequence 3.
    Column 3 will be sort sequence 1.
    This was working in 3.0 and now the report only acknowledges the sort sequence of number 1.

    Did you ever get this working again? We'd like to implement something similar - allowing the user to pick a couple of different sort criteria options... How did you implement this in 3.0?
    Thanks,
    Yvette

  • Af:column (tr:column) sortProperty for multiple field sort

    I'm using JDeveloper 10.1.3.5, but this ought to apply to Trinidad in 11g as well. In ADF Faces 10g there is a sortProperty attribute of af:column (or in Trinidad, tr:column) that takes the name of the field to use to re-sort the table, if the user clicks the column header. But I have a column that contains an entire address: Street Address, City, State, and Zip-Code as separate af:outputText components. Is there a way to tell it to sort the address on State, then City, then Zip-Code? The best I can do now is to set sortProperty to "zipCode", but that isn't really right.

    Hi,
    Yes and no, sadly. We reimplemented the table component partly for that on our project. Anyway, the workaround is to create a transient attribute on your row instance that returns a Comparable containing, or able to refer to, all three values (state, city, zip) and set the sortProperty on that dummy property (it does not have to be the same as the one actually shown in the page).
    Regards,
    ~ Simon

  • LookUpSet is Not working for multiple columns in SSRS 2008 R2

    Hi Friends,
    I have a problem when i use more than one LookUpSet in SSRS to display more than one value based on Day Number & other fields..Please find the below details and please suggest me a solution for this.
    Crystal : 
                    Day1                              Day2
    Period 4     Arts,Maths               Arts,Maths
    For this in SSRS i am using LookUpSet as below based on StaffID,PeriodNumber & DayNumber like  this:
    = (IIF(Fields!DayNumber.Value=1,Join(LookupSet(Fields!StaffID.Value & Fields!PeriodNumber.Value &  Fields!DayNumber.Value
        , Fields!StaffID.Value & Fields!PeriodNumber.Value & Fields!DayNumber.Value
        , Fields!ClassCode.Value
        , "TIMSTF5"), "," ),"")) 
    which is displaying correct in SSRS,But when i use the same expression to display Day 2 classes it is returning empty even though i have values on Day 2.Please have a look at the SSRS output below:
                    Day1                              Day2
    Period 4     Arts,Maths              
    Day 2 Expression is :
    = (IIF(Fields!DayNumber.Value=2,Join(LookupSet(Fields!StaffID.Value & Fields!PeriodNumber.Value &  Fields!DayNumber.Value
        , Fields!StaffID.Value & Fields!PeriodNumber.Value & Fields!DayNumber.Value
        , Fields!ClassCode.Value
        , "TIMSTF5"), "," ),""))
    I am not sure why it is not liking to use more than LookUpSet in the same report,Please suggest me with a work around for this.
    Thanks in advance,
    Sam.

    Hi Guys,
    I have sorted out the problem.Solution for the above problem is use Max before the expression like below, since it has multiple days and periods in the Dataset.
    = Max((IIF(Fields!DayNumber.Value=2,Join(LookupSet(Fields!StaffID.Value & Fields!PeriodNumber.Value &  ields!DayNumber.Value
        , Fields!StaffID.Value & Fields!PeriodNumber.Value & Fields!DayNumber.Value
        , Fields!ClassCode.Value
        , "TIMSTF5"), ","  + vbcrlf),"")))
    Thanks,
    Sam

Maybe you are looking for