Order by -- complex sorting?

Hello:
How can one accomplish the following:
Let's say I have the following scenario:
Select value2 from table2 IF this value exists. Else, select value 1 from table1. --
Then: I would like to ORDER BY all of the above results (sometimes the value may be value1, other times vaule2, etc). How can one do such an ORDER BY? Is this even possible via a query?

Hi,
In most cases, you can use functions and CASE expressions (or more specialized if-then-else expressions, like COALESCE) to sort things the way you want.
For example, if you want to pass a parameter, :p_sort_key, a VARCHAR2 that tells if you want to sort by value1, value2or value3, then you can do this:
ORDER BY  CASE  :p_sort_key
          WHEN  'V1'  THEN value1
          WHEN  'V2'  THEN value2
          WHEN  'V3'  THEN value3
             ENDThis assumes value1, value2 and value3 all hafve the same datatype. If not, use TO_CHAR or some other conversion function on one or more of them.
Now say we want to sort by table2.value4 if it is present, and otherwise by the expression above.
Depending on your exact requirements, you could say
ORDER BY  table2.value4               NULLS LAST
,            CASE  :p_sort_key
          WHEN  'V1'  THEN value1
          WHEN  'V2'  THEN value2
          WHEN  'V3'  THEN value3
             ENDThis will sort by table2.value4, and then, as a tie-breaker, by the other value. (NULLS LAST is the default, so you don't have to say explicitly say it, but you can for clarity's sake.)
if you really want the second expression only to have effect when table2.value2 is NULL, then you could use a NVL statement, or incorporate value4 into the CASE:
ORDER BY  CASE 
          WHEN  table2.value4  IS     NOT NULL
                                      THEN table2.value4
          WHEN  :p_sort_key = 'V1'  THEN value1
          WHEN  :p_sort_key = 'V2'  THEN value2
          WHEN  :p_sort_key = 'V3'  THEN value3
             ENDIf all else fails, there's always dynamic SQL.
In SQL*Plus, for example, you could run a preliminary query that produces a sting like
SUBSTR (value1, 1, 2),
value3,
TRUNC (entry_date, 'YYYY') and sets the substitution variable &order_txt to that value.
Then, in your main query, you say:
ORDER BY  &order_txt

Similar Messages

  • I'm actually trying to find the date i visited a site. adding columns allow the order to be sorted but not show a date. Please tell me it there's a way to see t

    I'm actually trying to find the date i visited a site. adding columns allow the order to be sorted but not show a date. Please tell me it there's a way to see the date. the sidebar no longer has the option for date. the most recent only shows the time.

    If you only see the time then that would mean that you see an entry of the current day (today).
    History items from past days should have the date as well in the Most Recent Visit column.
    You should be able to see this changing if you open the last 7 days folder and scroll down.

  • Difference between ordered by and sorted by?

    hi,
    Can any1 tell me wats the actual difference between ordered by and sorted by???

    Generally speaking, when talking math, one talks about an "ordering" in some set of values. Usually one doesn't actually place them in order; the order is already there, implicit in the values. When talking computer science, one talks about "sorting" because the values may be in a sequence which violates the desired order, and you have to sort the sequence to match the order. "Sorting" isn't as relevant in math because there is no sense of the items being out of sequence when the order is established.
    So "order" describes the ideal (which mathematicians care about).
    "Sort" describes the practical, the activity needed to make the real match the ideal (which computer sciences care about).
    That's my intuitive feeling on it, anyway.

  • I submitted my podcast and I got an email saying error, I checked with the feed validator and got this message: This feed does not validate. line 40, column 6: Undefined item element: itunes:order, how do sort this out, someone help me please.

    I submitted my podcast and I got an email saying error, I checked with the feed validator and got this message: This feed does not validate. line 40, column 6: Undefined item element: itunes:order, how do sort this out, someone help me please.

    Ignore it. 'itunes:order' is a recent addition which FeedValidator doesn't know about. If your podcast is rejected that is unlikely to be the reason. Of course as you haven't posted the feed URL nor the text of the error message I can't make any further comment.

  • How to change the sort order of complex table in drop down

    Hi Team,
    I have a complex table which is working but the sort order i want in a different way. How can i change?
    Regards,
    Gupta

    Gupta,
    My screen field definitions are as follows:
    1. Location
    2. Partner
    --In my previous reply, the first screen shot is without any parent index. So it is giving all values in alphabetical order only.
    --After that I created parent index for partner with location, So the partner values are depend on location chosen.
    In my TEST1:
    --I just selected "Andhra pradesh" as location, In partner field drop down it is showing "Ragava" "Suman" "Sunitha" only.
    --Because these are only the values belong to "andhra pradesh" location and these are coming in alphabetical order only.
    TEST2:
    --Here I selected "Gujrat" as location, In partner field drop down it is showing "Avinash" "Mohan" "Suman" which are belong to "Gujrat" location, These are also in alphabetical order only.
    Hope this clears now. Still any query please post.
    Thanks,
    Swaroopa.

  • Sort order in iTunes (sort by album)

    Hi!
    What could be the cause that iTunes in this case: http://homepage.mac.com/bhager/sortierung.png doesn't sort the tracks in correct order when sorting by album? In the other cases apparently it works fine.
    Thanks,
    Bensch

    I had this problem when I was viewing the tracks in "Group by Artwork" mode. It would "duplicate" the album and the artwork for every change in Artist.
    Here's a solution if you don't want to rename all the tracks with s single artist (if there is more than one):
    - Select all the tracks in the album
    - Click command + I
    - In the field "Album Artist" enter a single space (" ")
    That's it. All the tracks will be grouped together.
    Enjoy!
    17" PowerBook   Mac OS X (10.4.6)   1.67 Ghz G4, 2 GB RAM

  • How do I get my Music library songs in alphabetical order and not sorted by artist?

    Curious how you can sort your songs by alphabetical order without them being grouped by artist? Having this problem on ipad and iPhone

    Well as far as I can recall, I did nothing special at all when I synced my music to the iPad. I have very few downloaded/purchased songs on the device, but even the very few purchased songs that I have in the Music App are in alphabetical order. The only settings that can be changed on the iPad are in Settings>Music and I don't see anything in there that has any bearing in this. I have Group by Album Artist selected, but that doesn't change the alphabetical order if I toggle it off and on.

  • My Album Order Doesn't Sort Correctly in iTunes

    Hi, I don't know whether anyone can help me with this, but I'd like my albums to sort such that the songs are in the same order in my iTunes as they are on the album. For example, right now I have 3 John Mayer albums in my iTunes and iTunes mixed all the albums up from the CDs such that the right songs don't follow in iTunes. I'm guessing this is not hard to figure out, but I'm a bit of a techno idiot. Thanks for any help someone might be able to provide.
    Thanks,
    Keri
    [email protected]

    Hi, Keri.
    ... I'd like my albums to sort such that the songs are in the same order in my iTunes as they are on the album.
    Generally speaking, that will be the case if you click on the Album column heading in your main iTunes Library display.
    Can you confirm whether or not such is the case?

  • Play Order on Album Sort by Year Funk

    I was super pleased to find that iTunes 9.01 fixed the bug regarding sorting multi-disc albums while sorting album by year.
    However, now I'm noticing that when I'm playing an artist's discography, while sorted by year, instead of playing the albums in chronological order (like they've been visually sorted), it plays the albums in alphabetical order (default sort). So I could be playing an artists' first of five albums, but if the album name starts with a 'Z' then it will just stop the playlist all together, as if the end of said playlist has been reached.
    Also, does anyone else who sorts by year find it annoying that iTunes finds it prudent to always switch back to sorting by album alphabetically whenever I'm not looking? I find that quite annoying.
    Any ideas? Thoughts? Thanks!

    Oh poop. I just updated the two extensions "I Love Stars" and "Cover Stream."
    I'm no longer having problems with my music stopping after 'all' of an artists' music plays 'all' through. But still, anyone else having similar issues?
    Message was edited by: tyPod18
    Message was edited by: tyPod18

  • Performance - using JDBC call with 'order by' vs sorting data on app server

    Hello! I need some valid thoughts on the performance of using a JDBC call versus processing information on the application server.
    Here is the somewhat simplified scenario:
    I need to retrieve customer information (name, e-mail, telephone), display it in HTML format and then be able to redisplay it in a different order. For example, initially the list would be displayed sorted by last name, but then a user might choose to sort it by e-mail address. Initial call to DB uses 'order by' in the SQL stmt to get me the initial ordering by last name. Results are stored in 2D array. However, when a user selects a different sort I have two options:
    1) just make another call to the DB with a different order by clause. This means I need to create a DB connection, connect to DB, retrieve the results and read them from result set into a 2 dimensional array
    2) re-sort data in the 2D array populated during the initial call. This means I need to use java.util.Arrays.sort(my_2D_resultsArray, my_custom_comparator)
    Question is : which is more efficient? Number of entries retrieved can be anywhere from 0 to a few thousands (depending on other filters such as customer's country). My feeling is that option umber 2 is better, but I would like to get your opinion.
    Thank you!

    Good points! Thanks! I ran a test (see code below) and it takes less than a second to sort 2000 Strings and 2000 nulls. The only thing I ran the test at a UNIX prompt as oppose to from within app server (Weblogic). I expect the speed to be compatible though. Do you think that test was valid and tells us that sorting on the app server is probably faster than doing another SQL query?
    import java.io.*;
    import java.math.*;
    import java.util.*;
    import java.util.Arrays.*;
    public class Test {
      public static void main(String[] args) throws Exception {
        Test test = new Test();
        test.testSortingPerformance();
      public void testSortingPerformance() {
        Object[] objArray2 = new Object[]{};
        Vector v = new Vector();
        Date start, end;
        java.util.Random rd = new java.util.Random(2000);
        for (int i = 0; i < 2000; i++){
          v.add(new Object[]{new String("" + rd.nextInt())});
          v.add(new Object[]{null});
        objArray2 = v.toArray();
        Object[] innerObjArray2 = new Object[]{};
        MyComparator2 myComp = new MyComparator2();
        start = new Date();
        java.util.Arrays.sort(objArray2, myComp);
        end = new Date();
        for (int i = 0; i < objArray2.length; i++) {
          System.out.println();
          innerObjArray2 = (Object[])objArray2;
    for (int j = 0; j < innerObjArray2.length; j++) {
    System.out.print(innerObjArray2[j] + " ");
    System.out.println(v.size());
    System.out.println("Start " + start + " End " + end);
    import java.util.*;
    public class MyComparator2
    implements Comparator {
    //position in the inner array to use for comparison
    private int position = 0;
    //default empty constructor
    public MyComparator2() {
    //implement compare method
    public int compare(Object o1, Object o2) {
    Object[] strAr1 = (Object[]) o1;
    Object[] strAr2 = (Object[]) o2;
    if (strAr1[0] == null){
    if (strAr2[0] == null){
    return 0;
    else{
    return -1;
    else if (strAr2[0] == null){
    return 1;
    return ( (String) strAr1[0]).compareTo( (String) strAr2[0]);

  • Order by disk sort porblem

    hi friends i have a querry which return 40.000 rows and 2 mb data. this querry works in 1-2 seconds. if i add simple order by to querry it work in 20 seconds.
    i think because of disk sort. but i have another querry which have 270.000 row and 8 mb data its dont do disk sort. i write my querry, and in my opinion something force it disk sort instead of ram and row. but i dont find the problem.
    thanks
    SELECT p.nkisi_uygulama_id, p.nvardiya_id,
              p.dbaslangic_tarih AS dper_vardiya_bas_tarih,
              p.dbitis_tarih AS dper_vardiya_bit_tarih, p.nper_vardiya_id,
              v.nvad AS nvvardiya_ad, v.nvaciklama, v.nvbaslama_saat,
              v.ntoplam_saat, TO_CHAR (d.tarih, 'DAY') AS nvgun,
              TO_DATE (d.tarih || ' ' || v.nvbaslama_saat,
                       'DD.MM.YYYY HH24:MI'
                      ) AS dbaslangic_zaman,
                TO_DATE (d.tarih || ' ' || v.nvbitis_saat,
                         'DD.MM.YYYY HH24:MI'
              + CASE
                   WHEN TO_DATE (d.tarih || ' ' || v.nvbitis_saat,
                                 'DD.MM.YYYY HH24:MI'
                                ) <
                          TO_DATE (d.tarih || ' ' || v.nvbaslama_saat,
                                   'DD.MM.YYYY HH24:MI'
                      THEN 1
                   ELSE 0
                END AS dbitis_zaman,
              (SELECT bvardiya_izin
                 FROM iky_tnm_vardiya_gun vi
                WHERE vi.nvardiya_id = v.nvardiya_id
                  AND TO_CHAR (d.tarih, 'D') =
                         CASE
                            WHEN vi.ntip_gun_id = 781
                               THEN 1
                            WHEN vi.ntip_gun_id = 782
                               THEN 2
                            WHEN vi.ntip_gun_id = 783
                               THEN 3
                            WHEN vi.ntip_gun_id = 784
                               THEN 4
                            WHEN vi.ntip_gun_id = 785
                               THEN 5
                            WHEN vi.ntip_gun_id = 786
                               THEN 6
                            WHEN vi.ntip_gun_id = 787
                               THEN 7
                         END) AS bvardiya_izin
         FROM iky_tnm_vardiya v,
              iky_hrk_per_vardiya p,
              TABLE (pck_iky_func.f_tbl_per_vardiya_zaman ()) d
        WHERE p.nvardiya_id = v.nvardiya_id
          AND d.ID = p.nper_vardiya_id
          AND p.nvardiya_id IS NOT NULL
          AND TO_CHAR (d.tarih, 'D') IN (
                 SELECT CASE
                           WHEN g1.ntip_gun_id = 781
                              THEN 1
                           WHEN g1.ntip_gun_id = 782
                              THEN 2
                           WHEN g1.ntip_gun_id = 783
                              THEN 3
                           WHEN g1.ntip_gun_id = 784
                              THEN 4
                           WHEN g1.ntip_gun_id = 785
                              THEN 5
                           WHEN g1.ntip_gun_id = 786
                              THEN 6
                           WHEN g1.ntip_gun_id = 787
                              THEN 7
                        END
                   FROM iky_tnm_vardiya_gun g1
                 WHERE
                        v.nvardiya_id = g1.nvardiya_id)
    ORDER BY nkisi_uygulama_id;

    Listen to Billy & Centinul. You'll need to figure out why the query is really slow, and the notes on tuning should help.
    Looking at your query: the sorting won't help performance. Make sure it is not sorting to disk (you can use AUTOTRACE in SQL*PLUS or SQL*DEVELOPER for this).
    Select list inline views are notorious for a couple of reasons. First, they can decrease performance by executing for every row. Second, under just the wrong conditions their actvity will not show up in execution plans - I just rewrote one as a insert/select from in 10gR2 to PL/SQL and the original execution plan only showed the insert with a cost of 2 (!); this is standard behavior on 9i (in my case I was able to consolidate multiple queries with a possible 50% per-line run time according to dbms_profiler).
    Table functions are also problematic for a couple of reasons - they provide needed functionality, but due to the converstion there are no statistics available to effectively plan out the execution by the CBO. The cardinality hint might help this somewhat but you have to hard-code the numbers. Sometimes the despised rule-based optimizer can help with conversions where there are no statistics available but this needs to be examined very carefully
    SQL looks so much more impressive when used with foreign languages :)

  • Sqlite 'Order By' not sorting

    Hi, I want to sort the results of an sqlite SELECT statement by a column containing NSDate values
    const char *sql = "SELECT roundsDate, value1, value2, value3 FROM round WHERE primaryKey=? Order By roundsDate DESC";
    The results are always in ascending order.
    Anyone any suggestions on how I get the results order by the 'roundsDate' column in descending order?

    Mir
    Anywhere are you trying to setQuery on Viewobject that is associated with querybean results region. If that is the case then you should use vo.setFullSqlMode(FULLSQL_MODE_AUGMENTATION)
    Thanks
    AJ

  • In my Movies list, what order are movies sorted in when viewing the 'Unwatched' tab in grid view? Because it sure isn't 'by title' like I have selected.  What gives?

    Sample movie order:
    The Adventures of Buckaroo Bonzai
    Bella
    No Country for Old Men
    Breach

    So, turingtest2 has it exactly right... Unwatched movies view is sorted by Album Artist.  So here's a nice little fix for that... you can go through and manually copy the Name of the movie into the Album Artist field, but if you have a lot of movies in this category, it will be tedious.  A better option, is to go to www.dougscripts.com, and download the This Tag, That Tag applet.  You can find a link here.  You can then select ALL of your unwatched movies, run the applet, and elect to copy the movie Name into the Album Artist field.  Boom!  And since Doug has done such an awesome job of saving you a bunch of time and effort, throw him a little donation.
    Peace,
    Jared

  • Slideshow - Order of Images - Sorting

    The only sorting optons for collections and playing a slideshow are:
    Capture time
    Import order
    Edit time
    Edit count
    Rating
    Pick
    Color Label
    File Name
    File Extension
    File Type
    Aspect ratio
    User order
    Through a combination of ratings and color labels, I have trimmed 2400 photos to about 500. For the most part, I want the photos arranged in the order of the capture time. But for wide and closeup shots of the same scene, I want the wide shots to appear first in the slideshow, followed by the related close-up shots. At this point, and given the large number of photos for the slide show, the only alternative above that allows for rearranging the order is "User order".
    I don't see where the user specifies the input field or metadata for "user order." I thought it may be related to the order the user clicks images into the collection, but this is not the case.
    It appears there is no way to drag and drop or insert images using a mouse to rearrange the order. That would be ideal and consistent with the visual design of Lightroom.
    Can anyone help with rearranging the order? I don't want to edit the image capture time solely to rearrange a slideshow. This would be very cumbersome.
    Kent
    San francisco

    After more testing with a smaller sample, the user order is the sequence the photos were added to the collection. When I first experimented with this, the user order of my test sample was the same as image capture time because I did a massive import to the collection (rather than photo by photo). When I was expecting a different sort order for image capture vs user order, I did not realize the sort order in my particular situation would be identical.
    So the work-around to specify a precise order is to first select and edit all of the photos for inclusion or exclusion from the slideshow. Then add the draft slide show picks into a second collection one by one in the exact order desired in the final slideshow. For sorting the final collection, select the last option - User select.
    There should be an easier way to accomplish this task. With 500 photos to arrange in order, it would be easy to make a mistake and miss a photo or put one in the wrong place. Perhaps you could change the color code after adding a photo to a collection to help in keeping track of the rearranging / sorting. This adds time to the already slow and tedious process.
    Any other ideas?
    Kent
    San Francisco

  • Paul McCartney Pre-Order Problem with Sorting

    I pre-ordered the new McCartney album last week (at which point it downloaded the "Ever Present Past" single) and when it became available today I downloaded the rest fine, except "Ever Present Past" (which should be song number 2) had a different album title ("Ever Present Past Single" or something like that) and thus didn't sort correctly with the rest of the album... so I edited the track to match the same album name and correct track number (being very careful to make sure that all of the fields in the Get Info window match the other tracks, and that there are no invisible spaces throwing it off), but it refuses to sort with the rest of the album... even tried to rebuild the iTunes Library file but that didn't work either... just curious if anyone else has a similar problem and/or a possible solution. Thanks.

    This is ridiculous that this issue isn't being
    > addressed. Same problem here, and I guarantee that
    > I'm not alone.
    Check out the emails I got from Apple on this:
    "I understand that the single " Memory Almost Full" from the album you pre-ordered, will did not download with the album and now you're unable to listen to the album without it stopping to get to the single. Please note that re-downloading the album, will not resolve this issue. You are correct when you mentioned that this issue will happen because iTunes sees it as two different albums because it was downloaded separately. Don't worry. To resolve this issue, I recommend creating a playlist for the album itself. That way, you can arrange the contents of the album so that they will play without interruption.
    This article will show you how to do this:
    Organizing your music and video using playlists
    http://docs.info.apple.com/article.html?path=iTunesWin/7.0/en/517win.html
    I hope you continue to enjoy using the iTunes Store."
    Well, that's great...so not only do I have to isolate the album from the rest of my iTunes collection, it also does nothing to fix the issue on my iPod. So I responded to them as such, and got this response:
    "You did mention very valid points when stating your disappointment with the way pre-ordered albums are downloaded and Apple recognizes that no one is better qualified to provide feedback about iTunes than the people who use it.
    I encourage you to use the iTunes Feedback page to submit your comments:
    http://www.apple.com/feedback/itunesapp.html
    Your efforts to share your feedback are very much appreciated.
    I hope you continue to enjoy using the iTunes Store.
    Is this ridicuous or what? Unbelievable. If I bought a CD in a store and the tracks were incorrectly burned on the CD, the store would take it back or at least try to exchange it for a new copy that wasnt defective. This TECHNICAL ISSUE needs to be resolved.
    iMac 17" 1.83 GHz Intel, iBook G4 12.1"   Mac OS X (10.4.6)  
    iMac 17" 1.83 GHz Intel, iBook G4 12.1"   Mac OS X (10.4.9)  

Maybe you are looking for

  • Brother HL-2270DW no longer works on 10.8.2

    Can someone please advise why two Brother printers can no longer connect to their respective macs? I have  Bother HL-2270DW on OSX 10.8.2 that stopped working today for no reason. The printer appears to be offline. I have tried everything and spent h

  • 10.6.8 update keyboard issues

    ever since i did this update my keyboard has been going crazy -_- sometimes the following keys stop working untill i reset the pram and SMC *RFV4* all the keys stop working tell i reset the pram and smc its starting to get very annoying -_- im using

  • Sales office Mandatory at Initial Screen

    Dear experts, When we create a sales order in VA01 we need to maintain the sales office as Mandatory for certain sales area in the initial screen. Incompletion log doesnu2019t help because it will be controlled only at Overview or Header or Item Scre

  • Wrorng pricing procedure copied into sales order

    HI Scenario: I am creating sales order with reference to quotaion ,  but then wrong pricing procedure is being copied. I have check the pricing procedure determination everytihng is fine. Brief: In quotation  I have trading as well as manufacturing m

  • MC207 display module cover cracked

    Hello everyone! After some months of using my new white MacBook I've noticed that, due to a very hot airstream running through the vents on the lower back side, the part of the display module that is right above the rear vents has cracked. That wasn'