Kind of loop in sql? Any alternative?

Hi,
We have the following table
create table orders
order_id NUMBER(10),
vehicle_id NUMEBR(10),
customer_id NUMBER(10),
data VARCHAR(10)
order_id, customer_id and vehicle_id are indexed.
In this table are stored multiple orders for multiple vehicles.
I need an sql-statements which returns me the last 5 orders for each truck.
For only one vehicle its no problem:
select * from orders
where vehicle_id = <ID>
and rownum <=5
order by order_id desc;
But I need something like a loop to perform this statement for each vehicle_id.
Or is there any way to put it into a subselect?
Any ideas are welcome ;-)
Thanks in advance,
Andreas

Hello
Effectively by having the bind variable in there you are partitioning by customer and vehicle id, so by adding customer_id into the partition statement, the optimiser should be able to push the bind variable right down to the inner most view...
XXX> CREATE TABLE dt_orders
  2  (      order_id NUMBER NOT NULL,
  3         customer_id     NUMBER NOT NULL,
  4         vehicle_id      NUMBER NOT NULL,
  5         some_padding    VARCHAR2(100) NOT NULL
  6  )
  7  /
Table created.
Elapsed: 00:00:00.23
XXX> INSERT INTO dt_orders SELECT ROWNUM ID, MOD(ROWNUM,100),MOD(ROWNUM,100), lpad(
  2  /
10000 rows created.
Elapsed: 00:00:00.43
XXX> CREATE INDEX dt_orders_i1 ON dt_orders(customer_id)
  2  /
Index created.
Elapsed: 00:00:00.17
XXX> select *
  2  from (
  3  select o.*, rank() over(partition by vehicle_id order by order_id desc) rk
  4  from dt_orders o
  5  where customer_id = :var_cust_id
  6  )
  7  where rk <= 5;
5 rows selected.
Elapsed: 00:00:00.11
Execution Plan
Plan hash value: 3174093828
| Id  | Operation                     | Name         | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT              |              |   107 | 11128 |    22   (5)| 00:00:01 |
|*  1 |  VIEW                         |              |   107 | 11128 |    22   (5)| 00:00:01 |
|*  2 |   WINDOW SORT PUSHED RANK     |              |   107 |  9737 |    22   (5)| 00:00:01 |
|   3 |    TABLE ACCESS BY INDEX ROWID| DT_ORDERS    |   107 |  9737 |    21   (0)| 00:00:01 |
|*  4 |     INDEX RANGE SCAN          | DT_ORDERS_I1 |    43 |       |     1   (0)| 00:00:01 |
Predicate Information (identified by operation id):
   1 - filter("RK"<=5)
   2 - filter(RANK() OVER ( PARTITION BY "VEHICLE_ID" ORDER BY
              INTERNAL_FUNCTION("ORDER_ID") DESC )<=5)
   4 - access("CUSTOMER_ID"=TO_NUMBER(:VAR_CUST_ID))  <----
Note
   - dynamic sampling used for this statement
Statistics
         36  recursive calls
          0  db block gets
        247  consistent gets
          2  physical reads
          0  redo size
        518  bytes sent via SQL*Net to client
        239  bytes received via SQL*Net from client
          2  SQL*Net roundtrips to/from client
          1  sorts (memory)
          0  sorts (disk)
          5  rows processedyour original statement showing that the bind variable has been applied to access the dt_orders table via the index (predicate 4)
If I change the statement to put the bind variable outside the inline view, we now do a full scan and you can see from predicate 1 that the customer id is being filtered at the highest level.
XXX> select *
  2  from (
  3  select o.*, rank() over(partition by vehicle_id order by order_id desc) rk
  4  from dt_orders o
  5  )
  6  where rk <= 5
  7  AND customer_id = :var_cust_id ;
5 rows selected.
Elapsed: 00:00:00.32
Execution Plan
Plan hash value: 3560032888
| Id  | Operation                | Name      | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT         |           | 10696 |  1086K|       |   268   (2)| 00:00:04 |
|*  1 |  VIEW                    |           | 10696 |  1086K|       |   268   (2)| 00:00:04 |
|*  2 |   WINDOW SORT PUSHED RANK|           | 10696 |   950K|  2216K|   268   (2)| 00:00:04 |
|   3 |    TABLE ACCESS FULL     | DT_ORDERS | 10696 |   950K|       |    39   (3)| 00:00:01 |
Predicate Information (identified by operation id):
   1 - filter("RK"<=5 AND "CUSTOMER_ID"=TO_NUMBER(:VAR_CUST_ID))  <---
   2 - filter(RANK() OVER ( PARTITION BY "VEHICLE_ID" ORDER BY
              INTERNAL_FUNCTION("ORDER_ID") DESC )<=5)
Note
   - dynamic sampling used for this statement
Statistics
          4  recursive calls
          0  db block gets
        240  consistent gets
          0  physical reads
          0  redo size
        519  bytes sent via SQL*Net to client
        239  bytes received via SQL*Net from client
          2  SQL*Net roundtrips to/from client
          1  sorts (memory)
          0  sorts (disk)
          5  rows processedBut those two statements are really the same. By applying the filter inside the view as in your original, it means it's only going to calculate the rank for those customers. So we can add the customer id to the partition by statement which means the optimiser can safely push the predicate back down to the access of the orders table..
XXX> select *
  2  from (
  3  select o.*, rank() over(partition by customer_id,vehicle_id order by order_id desc) rk
  4  from dt_orders o
  5  )
  6  where rk <= 5
  7  AND customer_id = :var_cust_id ;
5 rows selected.
Elapsed: 00:00:00.04
Execution Plan
Plan hash value: 3174093828
| Id  | Operation                     | Name         | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT              |              |   107 | 11128 |    22   (5)| 00:00:01 |
|*  1 |  VIEW                         |              |   107 | 11128 |    22   (5)| 00:00:01 |
|*  2 |   WINDOW SORT PUSHED RANK     |              |   107 |  9737 |    22   (5)| 00:00:01 |
|   3 |    TABLE ACCESS BY INDEX ROWID| DT_ORDERS    |   107 |  9737 |    21   (0)| 00:00:01 |
|*  4 |     INDEX RANGE SCAN          | DT_ORDERS_I1 |    43 |       |     1   (0)| 00:00:01 |
Predicate Information (identified by operation id):
   1 - filter("RK"<=5)
   2 - filter(RANK() OVER ( PARTITION BY "CUSTOMER_ID","VEHICLE_ID" ORDER BY
              INTERNAL_FUNCTION("ORDER_ID") DESC )<=5)
   4 - access("O"."CUSTOMER_ID"=TO_NUMBER(:VAR_CUST_ID))  <----
Note
   - dynamic sampling used for this statement
Statistics
          9  recursive calls
          0  db block gets
        244  consistent gets
          0  physical reads
          0  redo size
        519  bytes sent via SQL*Net to client
        239  bytes received via SQL*Net from client
          2  SQL*Net roundtrips to/from client
          1  sorts (memory)
          0  sorts (disk)
          5  rows processedHTH
David

Similar Messages

  • Any alternatives to adobe flash?  Kind of a drag not being able to veiw certain content

    Any alternatives to adobe flash?  Kind of a drag not being able to view content?  I love my iPad and will be an apple head for the rest of my days, but, adobe flash thing is a pain.

    There are no ideal solutions as flash isn't supported, but depending on what sites you are trying to access, you might find that some of them (probably more so if they are news sites) have their own apps in the App Store which might let you get some of the content that you want (and there is the built-in YouTube app). Also there are browsers such as Skyfire which 'work' on some sites - but judging by the reviews not all sites. If you want to play flash games then you are probably out of luck if you want to play on-line though the iSwifter app might work on some of them, but again some flash games have app versions in the store.

  • Is there any alternative to set serveroutput on

    without having to use the set serveroutput on can i make the results display using dbms_output.put_line.i have tried using dbms_output.enable on somebody's advise.
    begin
    dbms_output.enable;
    dbms_output.put_line('xyz');
    end;
    but the above one is not displaying the result if i don't use set severoutput on. is it must to use set serverout on.is there any alternative keyword or somthing which i can embed in pl/sql block itself to display the result.
    thank you.

    pl/sql is not a user interface tool. It cannot display anything. There are various ways to get to see output from it but whatever method must involve some other facility which has the ability to display stuff.

  • Disk utility no longer working, any alternative HDD maintenance prog?

    Hi all,
    I have an early 2003 Powerbook G4 12" aluminium. 80Gb HDD with about 4.5Gb free. It's running very slowly but I hardly tax the machine so I'm not too bothered, but I tried to run Disk Utility to make sure everything was ok and it couldnt even verify permissions. It said it might take several minutes to run the permissions, but after 20+ minutes I gave up.
    Is there any alternative free program that'll check all the important bits and make sure things are fine?
    I used to use OS9 and ran things like Techtool lite and Norton speedtools; zapping the PRAM, optimising the drive and that sort of thing. I get the feeling the HDD on this powerbook is fragmented to ****, but then I didn't think Macs slowed down from such things like a PC.
    But its made me realise I don't have any kind of housekeeping tools to keep my now OSX machines running (those being the G4 powerbook and a Quicksilver G4, running Leopard and Tiger respectively).
    Many thanks for any help.

    Are you running Disk Utility using your Tiger install DVD? If not, you need to.
    Another popular utility is Disk Warrior (more powerful than DiskUtility), however, it costs about $100.
    You don't have enough free space on your hard drive as it is typically recommended to have 10-15% free.
    Mac OS X: System maintenance
    http://discussions.apple.com/thread.jspa?messageID=607640
    Mac Tune-up: 34 Software Speedups
    http://www.macworld.com/article/49489/2006/02/softwarespeed.html
    52 Ways to Speed Up OS X
    http://www.imafish.co.uk/articles/post/articles/130/52-ways-to-speed-up os-x/
    Tuning Mac OS X Performance
    http://www.thexlab.com/faqs/performance.html
    11 Ways to Optimize Your Mac's Performance
    http://lowendmac.com/eubanks/07/0312.html
    The Top 7 Free Utilities To Maintain A Mac.
    http://mac360.com/index.php/mac360/comments/the_top_7_free_utilities_to_maintain _a_mac/
     Cheers, Tom

  • Is there any alternative for OVS ?

    Hi All,
        I am looking for alternative method to implement help option to multiple input fields. So, I wanted to ask memebers of this forum if there is any alternative approach to achieve this functionality as I find implementing OVS is very confusing and time consuming.
    Kindly suggest me if there is any alternate option if available. I tried Hotel Reservation example and flight reservation examples.
    Kindly suggest me any new methods.
    Thanks
    Uday

    I would first develop a view which will act as your value selector (I would use a table UI element with filtering capabilities)
    Then embed this view in a window so it can be shown as a popup using code in the onEnter event, like
    IWDWindowInfo winInfo = (IWDWindowInfo)wdComponentAPI.getComponentInfo().findInWindows("YourValueSelectorWindow");
    IWDWindow     win     = wdComponentAPI.getWindowManager().createModalWindow(winInfo);
    win.setWindowPosition (<left_relativ_to_your_inputfield>, <top_relative_to_your_inputfield>);
    win.setWindowSize (<width>,<height>);
    win.show();
    In this window bind your table UI element to the context of your source data, implement filtering capabilities, and upon selection pass the desired value back to the parent inputfield and closing the popup window.

  • REJECT is obsolete in ECC 6.0 - Any Alternative?

    Hi Developers,
    REJECT statment is used to break from GET event (say GET PERNR event in Logical Database) used to process for an Employee.
    This REJECT statement is Obsolete . Is there any alternative for this ?
    If so, please reply at the earliest as it is very Urgent.
    Regards,

    Use check statement.
    Demo is as follows -
    constants: c_1(1) type c value '1' .
    Start-of-selection.
    get pernr.
    Read Infotype 0
    rp-provide-from-last p0000 space pn-begda pn-endda.
    check pnp-sw-found eq c_1. "it will check if record is there,if not it will go to next pernr

  • Is there any alternative to GUI_DOWNLOAD  other than  WS_DOWNLOAD?

    Hi All,
    Is there any alternative FM other than GUI_DOWNLOAD and WS_DOWNLOAD?I need to download a PDF file to a network drive.
    Thanks in Advance,
    Anjaly

    Hi,
    If u want to download a PDF file from application server...
    u can use the transaction...  <b>CG3Y</b> directlyy..
    just check it and use it in ur program..
    cheers,
    Simha.

  • Any alternative FM for GUI_DOWNLOAD other than WS_DOWNLOAD?

    Hi All,
            Is there any alternative FM other than GUI_DOWNLOAD and WS_DOWNLOAD?I need to download a PDF file to a network drive.
    Thanks in Advance,
       Anjaly

    check this thread
    ITS Upload / Download using CL_GOS_MANAGER
    Raja

  • In JDBC Sender Adapter , the server is Microsoft SQL .I need to pass current date as the input column while Executing stored procedure, which will get me 10 Output Columns. Kindly suggest me the SQL Query String

    In JDBC Sender Adapter , the server is Microsoft SQL .I need to pass current date as the input column while Executing stored procedure, which will get me 10 Output Columns. Kindly suggest me the SQL Query String , for executing the Stored Procedure with Current date as the input .

    Hi Srinath,
    The below blog might be useful
    http://scn.sap.com/community/pi-and-soa-middleware/blog/2013/03/06/executing-stored-procedure-from-sender-adapter-in-sap-pi-71
    PI/XI: Sender JDBC adapter for Oracle stored procedures in 5 days
    regards,
    Harish

  • Reports included in the page keep looping without retrieving any results

    We are facing an issue related to the behaviour of Siebel Analytics when more than 1 answer are included in a dashboard page. When a report is generated, the other reports included in the page keep looping without retrieving any results, but if I manually click on 'cancel' link, the reports successfully appear with consistent data. This behaviour is not stable since sometimes the page works fine, sometimes not, but it's not clear what it depends on. Can anybody please let me know if this behaviour is a known bug.

    Hi Deb,
    Could you please explain me in more detail?
    The problem is we are able to see the old reports that we were already moved into Q environment. The newly moved 5 reports are giving this error message.
    Please help
    Thanks
    Sri

  • Any alternative to the BADI for scaled pricing in CCM catalogs

    Hi,
    We are not able to use the scaled pricing functionality in CCM. When the item is added to the shopping cart from the CCM catalog the highest price gets chosen by default irrespective of the quantity ordered.
    I understand that this can be solved by activating the BADI /CCM/CSE_ENRICHMENT and Implementation /CCM/CSE_OCISCALEPRI
    IS THERE ANY ALTERNATIVE TO THIS. CAN THIS FUNCTIONALITY OF SCALED PRICING BE ACHIEVED WITHOUT THIS BADI.
    Regards,
    Srivatsan

    Hi Srivatsan,
    you could use the BADI BBP_CATALOG_TRANSFER to amend the price, in order to do this you would need to pass the lower bound to one of the OCI custom fields in order to pick up this avlue and determine the correct price.
    Why do you not want to use the standard implementatiom though?
    Regards
    Chris

  • We tried the window.ResizeTo and window.MoveTo methods using the javascript. It doesn't seem to be working in the version 9.0.1. Please suggest any alternative .

    Hi,
    We tried the window.ResizeTo and window.MoveTo methods using the javascript. It doesn't seem to be working in the version 9.0.1. Please suggest any alternative .
    Thanks,
    Avinash

    This is no longer allowed for security reasons (bug 565541).<br>
    See https://support.mozilla.org/nl/questions/880032<br>
    https://developer.mozilla.org/en/DOM/window.moveTo<br>

  • Any alternative to ago function

    Hello,
    I am using obiee 11g.Trying to use ago function at quarter level with the date prompts as filter
    instead of year prompt but somehow the data is not matching properly.
    Would like to know if there is any alternative to ago function?
    I just want to calcultate the count(distinct(id)) for current and previous quarter,where the report gets filtered by date fields.
    The report has user column,quarter column and the currrentcount and previous count.
    like
    user1->Q1->10->19
    user1->Q2->20->10
    User3->Q1->11->26
    Any help on this please?
    Thanks

    Hello,
    Thanks for reply.
    Is the grain below quarter level?
    ------> Calc date is below quarter level in the time dimension,Time dimesnion has FS Year(level1)->FS Quarter(level2)->Cal Date and Time key(Time key is the primary key with the combination of cal date and the pk of some other table (level3))
    Does quarter exists as a field in your date dimension?
    --------->Yes Fs Quarter is a field/column in the table and in the dimension
    check if quarter is a chronological key, does your quarter contain year in it(2011-02)?
    -------->In each level i have key defined, also in the FS Quarter i have.
    In the level3 i have both the key defined as key but cal_date as pk.
    Yes, Data of the qtarter is in the form 2012-01.
    Do you have quarter in your report, without date field?
    --------->yes, the report has FS_qtr,count for current qtr,count for previous qtr using ago function
    and the filter used is cal_date>='01-JUN-11'
    facts->
    There is a view in the database which is being created for time dimesnion.
    The view has
    FS_Year , FS_Qtr , Calc_Date ,Cal_month , cal_qtr, TimeKey(PK) , Pk_from someother_table_acting_as_fk.
    Please let me know where i am going wrong?
    One more thing i would like to add if i use the filter as FS_YEAR>=2011 then the counts comes perfectly.Problem is with cal date field.Just not bale to understnd where i am i going wrong?
    Please help
    Thanks
    Edited by: user123 on Feb 10, 2012 11:00 AM

  • Internal API DCTaskFlowBinding.. any alternative to this.

    Hi All,
    -- Jdev: 11.1.1.4
    In a solution to get handle to the bindings inside a region from its parent I am using this API DCTaskFlowBinding.
    This is Internal api.. Is there any alternative api for this ?
    I know that we should avoid using internal api's but can use of DCTaskFlowBinding be seriously alarming.
    Please note that I am using this api's ONLY to get handles to internal attribute bindings to read values form it.
    Thanks
    Amit
    Edited by: Amit on Feb 7, 2012 10:16 AM
    Edited class name..

    The API I use for DCBindingContainer imports
    import oracle.adf.model.binding.DCBindingContainer;which doesnot look to me to be a internal class since it dosnot have internal anywhere in its package structure.
    What is the complete class path that your code refers to ?

  • Are there any alternatives for iphone backup extractor?

    Hi all,
    I find that the 'iphone backup extractor' program is very useful, however it is quite annoying that they limit the extraction to 4 files at a time and that we have to pay in order to get our own data files propperly. :S
    When I restore my old backup from iTunes, every new thing is gone, when I restore the backup I just made, the old backup stuff has gone. It just replaces each other.
    Apple should have their own software like this where you can extract what ever you want from your old backups and transfer it on to your phone, such as contacts for example.
    Anyway, I was wondering if there is any alternatives for this program, or any other way I can extract my backup files ?

    If you're on a Mac, there is a "free" iPhone backup extractor, but none that I know of for Windows. You could always code your own program, that would be free.
    Apple doesn't provide a mechanism to do this for the simple reason they don't want users screwing with the iPhone backup. Thus, none of these third-party programs are supported.

Maybe you are looking for

  • HT1495 two different apple id's on the same computer

    My girlfriend's laptop is about to die.  I am in the process of transfering all of her files over to my computer.  I want to set up my iTunes so that she can plug her iPhone into my computer whenever she needs to...but I want to make sure to keep her

  • Exporting Metadata In Bridge CS4

    Bridge CS3 used to have a decent metadata export script, CS4 seems not to have this feature. How do I export the metadata from multiple image files in CS4 as a file type readable by EXCEL?

  • Business one client

    Hi, i need to download business one client but i can't find when download it someone can help me? Regards Santino

  • OS x SERVER AVOID PUBLISH USER FOLDER

    Hello, I'm installing Mac OS X Server 3.1.1., I've created all the local users I needed and everything is OK. But when the users connect to the Server, they also connect to their respective  user folder. Is there a way to hide the  local user folder

  • Download and Set up PhotoShop Premier 12

    It is not working at all. I am losing hours that I will never get back.