How to preset the order of rows in the outer query of a correlated query ?

Good morning,
I have the following simple query:
select empno,
       ename,
       sal,
       sum(case
             when rn = 1 then sal
             else -sal
           end) over (order by sal, empno) as running_diff
   from (
         select empno,
                ename,
                sal,
                row_number() over (order by sal, empno) as rn
           from emp
          where deptno = 10
         );That calculates a running difference and uses "row_number() over (...)" which is an Oracle specific feature to do so. It yields the following result (which we will consider correct):
     EMPNO ENAME             SAL RUNNING_DIFF
      7934 MILLER           1300         1300
      7782 CLARK            2450        -1150
      7839 KING             5000        -6150I wanted to come up with a solution that was not Oracle specific different solution. I tried the following code:
(EDIT: after additional thought, that code is totally different in meaning and will never come close, to the above result. Consider it wrong and ignore this attempt altogether.)
select a.empno,
       a.ename,
       a.sal,
       (select case
                 when a.empno = min(b.empno) then sum(b.sal)
                 else sum(-b.sal)
               end
          from emp b
         where b.empno <= a.empno
           and b.deptno = a.deptno) as running_diff
  from emp a
where a.deptno = 10;but the result is
     EMPNO ENAME             SAL RUNNING_DIFF
      7782 CLARK            2450         2450
      7839 KING             5000        -7450
      7934 MILLER           1300        -8750which is a long way from the original result. I've tried everything I could think of to order the rows before the running difference is calculated but, have been unsuccessful.
Is there a way to change this second query --(without using Oracle specific features)-- without using windowing features that would yield the same result as the first query ?
Rephrase of the above question:
Is there a way, using plain vanilla SQL (that is aggregate functions and set operations such as joins and unions) to create a query that yields the same result as the first one ?
Also, this is not for production code. This is simply an exercise in set manipulation that I'd like to see a solution for.
Thank you for your help,
John.
Edited by: 440bx - 11gR2 on Jul 18, 2010 12:50 AM - correct "ho w" to "How"
Edited by: 440bx - 11gR2 on Jul 18, 2010 1:42 AM - struck out all references to row_number and windowing features being Oracle specific features.
Edited by: 440bx - 11gR2 on Jul 18, 2010 3:51 AM - Noted that my try is woefully wrong and restated the objective to make it clearer.

Hi, John,
One way to get a running total (which is basically what you want) is to do a self-join. Join each row (let's call it the current row, or c) to itself and everything that came before it (let's call this the previous row, or p), and do a regular aggregate SUM, like this:
WITH     got_base_sal     AS
     SELECT       deptno
     ,       2 * MIN (sal)     AS base_sal
     FROM       scott.emp
     GROUP BY  deptno
SELECT       c.deptno
,       c.empno
,       c.ename
,       c.sal
,       b.base_sal - SUM (p.sal)     AS running_diff
FROM       scott.emp     c
JOIN       scott.emp     p     ON     c.deptno     = p.deptno
                    AND     (     c.sal     > p.sal
                         OR     (     c.sal     =  p.sal
                              AND     c.empno     >= p.empno
JOIN       got_base_sal     b     ON     c.deptno     = b.deptno
WHERE       c.deptno     IN (10)
GROUP BY  c.deptno
,       c.empno
,       c.ename
,       c.sal
,       b.base_sal
ORDER BY  c.deptno
,       running_diff     DESC
;Output:
    DEPTNO      EMPNO ENAME             SAL RUNNING_DIFF
        10       7934 MILLER           1300         1300
        10       7782 CLARK            2450        -1150
        10       7839 KING             5000        -6150I said you basically want a runninng total. There are two differences between a running total and your requirements
(1) You want to have a total of the negative of what's in the table. That's trivial: use a minus sign.
(2) You want the first item to count as positive instead of negative. That's not so trivial. The query above counts all sals as negative, but adds an offset so that it appears as if the first item had been counted as positive, not negative.
You didn't say what you want to do in case of a tie (two or more rows having the same sal). The query above uses empno as a tie-breaker, so that all sals are calculated as if they were distinct. This is similar to what analytic functions do when the windowing is based on rows. If you want something similar to windowing by range, that might actually be simpler.
The query above calculates a separate running_diff for each deptno, similar to "PARTITION BY deptno" in analytic functions. You happen to be interested in only one deptno right now, but you can change the main query's WHERE clause, or omit it, and the query will still work. If you don't want this feature (analagoud to not having any PARTITION BY), it's easy to modify the query.
You could also get these results using a recursive WITH clause. That meets the criteria of avoiding analytic functions and Oracle-specific features, but not the one about using only plain, simple SQL features.

Similar Messages

  • How to preset the FM Statio

    Recently, I just got Zen Neeon as my MP3 player.
    I had manage to save the Audio tracks into my player but I got problem preseting FM station to my player.
    I wish to know how to preset the station?
    Or else I will need to keep on tuning for my station.
    Thanks!

    clefairy978,
    Enter FM radio mode, scroll to the FM channel you wanted and then push the scroller in to access the player menu. Scroll down to the option 'Save Preset' and select the preset location you wanted.
    Jason

  • How to use the out parameter of a transformation

    Hi All,
    I have a requirement where I need to move all the transformations from process flows to map.SO for each transformation I need to have 1 map which calls this transformation.I have 1 transformation which has both input and output parameter.If I use this transformation in mapping then how to use the out parameter of thsi transformation.This out parameter needs to beused in other mappings.Can soemone please help me.
    Thansk in advance

    Hi,
    I'm not quite sure what you are trying to do.
    What works: Connect the outgroup of a pre- or post-mapping process operator to the mapping output parameter operator..
    What does not work: Connect the outgroup of an operator that can return more than one row (e.g. table operator, filter, joiner ,...) to the mapping output parameter operator. The mapping output parameter just returns "one row", like a pl/sql function call.
    You cannot pass a "data stream" from one mapping to another. Maybe the pluggable mappings is what you are looking for.
    Regards,
    Carsten.

  • How to insert the select query result into table?

    How to insert the select query result into table?
    SELECT  top 20 creation_time  
            ,last_execution_time 
            ,total_physical_reads
            ,total_logical_reads  
            ,total_logical_writes
            , execution_count 
            , total_worker_time
            , total_elapsed_time 
            , total_elapsed_time / execution_count avg_elapsed_time
            ,SUBSTRING(st.text, (qs.statement_start_offset/2) + 1,
             ((CASE statement_end_offset 
              WHEN -1 THEN DATALENGTH(st.text)
              ELSE qs.statement_end_offset END 
                - qs.statement_start_offset)/2) + 1) AS statement_text
    FROM sys.dm_exec_query_stats AS qs
    CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st
    ORDER BY total_elapsed_time / execution_count DESC;
    Thanks,
    Tirumala

    1. SELECT INTO
    Below method will create table when data is inserted from one table to another table. Its useful when you need exactly same datatype as source table.
    Use AdventureWorks2008R2;
    Go
    ---Insert data using SELECT INTO
    SELECT AddressLine1, City
    INTO BothellAddresses
    FROM Person.Address
    where City = 'Bothell';
    GO
    ---VERIFY DATA
    Select AddressLine1, City
    FROM BothellAddresses
    ---DROP TABLE
    DROP TABLE BothellAddresses
    GO
    2. INSERT INTO SELECT
    Below method will need table to be created prior to inserting data. Its really useful when table is already created and you want insert data from
    another table.
    Use AdventureWorks2008R2;
    Go
    ---Create Table
    CREATE TABLE BothellAddresses (AddressLine1 NVARCHAR(60), City NVARCHAR(30))
    ---Insert into above table using SELECT
    INSERT INTO BothellAddresses(AddressLine1, City)
    SELECT AddressLine1, City
    FROM Person.Address
    where City = 'Bothell';
    ---VERIFY DATA
    Select AddressLine1, City
    FROM BothellAddresses
    ---DROP TABLE
    DROP TABLE BothellAddresses
    GO
    Regards,
    Vishal Patel
    Blog: http://vspatel.co.uk
    Site: http://lehrity.com

  • How to view the sql query?

    hi,
      how to view the sql query formed from the xml structure in the receiver jdbc?

    You can view SAP Note at
    http://service.sap.com/notes
    But you require SMP login ID for this which you should get from your company. The content of the notes are as follows:
    Reason and Prerequisites
    You are looking for additional parameter settings. There are two possible reasons why a feature is available via the "additional parameters" table in the "advanced mode" section of the configuration, but not as documented parameter in the configuration UI itself:
    Category 1: The parameter has been introduced for a patch or a SP upgrade where no UI upgrade and/or documentation upgrade was possible. In this case, the parameter will be moved to the UI and the documentation as soon as possible. The parameter in the "additional parameters" table will be deprecated after this move, but still be working. The parameter belongs to the supported adapter functionality and can be used in all, also productive, scenarios.
    Category 2. The parameter has been introduced for testing purposes, proof-of-concept scenarios, as workaround or as pre-released functionality. In this case, the parameter may or may not be moved to the UI and documentation, and the functionality may be changed, replaced or removed. For this parameter category there is no guaranteed support and usage in productive scenarios is not supported.
    When you want to use a parameter documented here, please be aware to which category it belongs!
    Solution
    The following list shows all available parameters of category 1 or 2. Please note:
    Parameter names are always case-sensitive! Parameter values may be case-sensitive, this is documented for each parameter.
    Parameter names and values as documented below must be used always without quotaton marks ("), if not explicitly stated otherwise.
    The default value of a parameter is always chosen that it does not change the standard functionality
    JDBC Receiver Adapter Parameters
    1. Parameter name: "logSQLStatement"
                  Parameter type: boolean
                  Parameter value: true for any string value, false only for empty string
                  Parameter value default: false (empty String)
                  Available with: SP9
                  Category: 2
                  Description:
                  When implementing a scenario with the JDBC receiver adapter, it may be helpful to see which SQL statement is generated by the JDBC adapter from the XI message content for error analysis. Before SP9, this can only be found in the trace of the JDBC adapter if trace level DEBUG is activated. With SP9, the generated SQL statement will be shown in the details page (audit protocol) of the message monitor for each message directly.
                  This should be used only during the test phase and not in productive scenarios.
    Regards,
    Prateek

  • How to transport the BW query's variable to BO  webi report

    Hi all
    I'd like to know how to transport the BW query's variable to BO 's webi . today ,I created a sap customer varible in my bw system to get the max calmonth in the active table.The varible in the BW side run's well ,but I use this query to build a new univers ,and created a new webi report base on this univers ,but the question is the webi report can't get the varible's value I wann to know how to transport the bw varible value to BO webi report
    Thanks and regards,
    Peter .zhu

    I have changed my variaable in my bw query ,I found if you use SAP default variable it is ok in BO side . So I get a guidline by SAP default variable ,I changed my customer variable in variables edite ,don't use 'ready for input' .And then the variable can be useful in BO side .
    Edited by: peter zhu on Jun 16, 2008 11:43 AM

  • How to use the "out" parameter in idl

    hello.idl:
    module HelloApp
    interface Hello
    string sayHello();
    void getPass(in string name,out string pass);
    HelloServer:
    public class HelloServer
    class HelloServant extends _HelloImplBase
    public void getPass(String name,org.omg.CORBA.StringHolder pass)
    System.out.println("Server pass = " + pass);
    if (name.equals("lxh"))
    pass = new org.omg.CORBA.StringHolder("1234");
    if (name.equals("cbj"))
    pass = new org.omg.CORBA.StringHolder("5678");
    HelloClient:
    public class HelloClient
    public static void main(String args[])
    try{
    org.omg.CORBA.StringHolder Pass = null;
    if (args.length == 1)
    System.out.println("Client pass = " + args[0]);
    helloRef.getPass(args[0],Pass);
    System.out.println(Pass);
    } catch(Exception e) {
    When I run client main method with parameter "lxh",I will get a error says the getPass() parameter which has given is wrong.
    How to use the out parameter in client?

    Does this error only occurs if you pass "lxh" or always?
    Did you try passing a StringHolder Object rather than a NULL Object?
    Perhaps you can post the error message!?

  • How to set the out point beyond 9.95 seconds???

    how to set the out point  in Motion 5 beyond 9.95 seconds???

    First you need to make sure your project is long enough then you can adjust the play range (in/out). To make sure the project is long enough:
    1. From the project properties (command-J) go to the Duration field and enter a new duration.
    2. Click on the down arrow icon to the right of the current time, there is an option to show the project duration. Once set to this you can double click the number and type in a new project duration. I'd recommend setting it back to show current time when done.
    3. Of course you can also change the duration of a project when it is first created, in the project browser.
    Once you're sure you have a long enough project you can adjust the in and out range.  You then use the zoom controls in the bottom of the timeline to show more of the timeline and adjust the play range as needed. There's lots more about project and play range duration adjustments in the documentation: http://help.apple.com/motion/mac/5.1/

  • How to analyzer the BI query in VISUAL COMPOSER?

    hi experts,
    could you please explain me how to analyze the Bex query in VISUAL COMPOSER? could you please provide me the step-by-step documentation if possible??
    regards
    vadlamudi

    Hi Vadlamudi,
    Here is some documentation for using BI Queries in VC:
    [Modeling Composite Views Using BI Data Services|http://help.sap.com/saphelp_nwce10/helpdata/en/46/081ed5f8685875e10000000a11466f/frameset.htm]
    [Maintaining BI System Connections|http://help.sap.com/saphelp_nwce10/helpdata/en/7e/6dbcea3700452195e3bddaa47c5906/frameset.htm]
    I hope it helps,
    Regards,
    Udi

  • How to extract the Physical Query(database Query)

    Hi ,
    How to extract the Physical Query(database Query) from obiee which was fired in obiee
    Regards
    Ranga

    Hi Ranganath,
    Have a look the following links.
    Setting Logging level:
    http://gerardnico.com/wiki/dat/obiee/loglevel
    How to see physical query:
    http://gerardnico.com/wiki/dat/obiee/manage_session_log
    If you are new to OBIEE, spend some hours on the following blog to learn from basics to advanced level.
    http://gerardnico.com/wiki/
    http://obiee101.blogspot.com/
    http://www.rittmanmead.com/blog/
    Hope it helps you.
    Regards,
    Kalyan Chukkapalli
    http://123obi.com

  • How to write the given query using 'ANY ' operator

    Hi,
    How to write the given query using 'ANY ' operator , I dont need to fetch to grade_master table twice in database, just need to fetch within the result set.
    SELECT dsg_code,dsg_name,dsg_grade FROM designation_master WHERE dsg_orgn='&&Orgn' and dsg_ctry='&&ctry'
    And dsg_loc ='&&loc' And dsg_oru = '&&oru' and dsg_grade in decode('&&radio_group',
    1, SELECT grd_code FROM grade_master WHERE grd_osm_code in (Select grd_osm_code FROM grade_master WHERE grd_orgn='&&Orgn' and grd_ctry='&&ctry' And grd_loc ='&&loc' And grd_oru = '&&oru' and grd_code ='&&emp_grade'),
    2, SELECT grd_code FROM grade_master WHERE grd_osm_code > (Select grd_osm_code FROM grade_master WHERE grd_orgn='&&orgn' and grd_ctry='&&ctry' and grd_loc ='&&loc' And grd_oru = '&&oru' and grd_code),
    3, SELECT grd_code FROM grade_master WHERE grd_osm_code < (Select grd_osm_code FROM grade_master WHERE grd_orgn='&&orgn' and grd_ctry='&&ctry' And grd_loc ='&&loc' And grd_oru = '&&oru' and grd_code ='&&emp_grade'))
    thanks
    rincy

    Hi,
    One thing I understood my your issue is you want to perform, execution of query once or fetch the results sets my minimizing the number of times executions of queries. It would be hard for us to check in this way, atleast provide some temporary data and some business rules. Only I can IN, >, < (queries logical conditons on inner query)
    - Pavan Kumar N
    - ORACLE OCP - 9i/10g
    https://www.oracleinternals.blogspot.com

  • How to Preset the Web Page resolution

    Hello to all. I tried searching but came with nothing. I
    wanted to know if there is a way in preseting the page to a
    resolution, say 1024x768
    Or is it better having the width set at 100% and go from
    there?
    thank you for the help

    Hi,
    >>
    I wanted to know if there is a way in preseting the page to a
    resolution, say 1024x768
    >>
    you could put all the page contents in a table that´s
    tagged with a fixed width of 1024
    >>
    Or is it better having the width set at 100% and go from
    there?
    >>
    I´d certainly recommend this "fluid" approach, because
    you can´t foresee if the visitor has a smaller screen
    resolution, or if part of the browser´s "inner screen" has
    been reduced by means of a sidebar.

  • RRI - How to edit the Receiver query

    Hello All,
    As per http://help.sap.com/saphelp_nw2004s/helpdata/en/e3/156e3fefa13042e10000000a114084/frameset.htm
    I created a Target for my query (sender). The target or receiver query is also a BeX query in the same system.
    Now in my sender query, I have Department in my rows and Employees in the columns. When I double click on Department, it takes me to Target but it does not show the report in the format I want. How do I modify the receiver query?
    Also if someone has good knowledge in RRI, it would be really helpful if you can help me out with my query?
    Thanks in advance
    Regards,
    Abhishek

    Hi Abhishek,
    -- Characteristics that are to be filled from the sender query should be defined as free characteristics. A hierarchy node restriction, for example, can also be transferred to free characteristics as a property.
    -- Changeable variables for the receiver query are not filled by the RRI.
    -- Selections for various InfoObjects are transferred if the InfoObjects have the same reference characteristic.
    When the RRI is called, the sender query transfers the following filters to the receiver query:
    ·        global filters
    ·        values in the navigation block (dynamic filters including the presentation hierarchy)
    ·        filters from the restricted key figure selected
    ·        filters from the drilldown characteristics selected
    The system first fills the variables and then fills the navigation block. In order to do this, a unique characteristic assignment must be possible. Selections for various InfoObjects can then be transferred, as long as the InfoObjects reference the same basic characteristic. Hierarchy nodes are triggered in selections and can then be transferred to the respective InfoObjects.
    See this link and if any further questions get back to me :
    http://help.sap.com/saphelp_nw04/helpdata/en/c9/bc2d38c4b3f205e10000009b38f8cf/frameset.htm
    Assign Points if Helps !!
    Regards,
    Naveen Rao Kattela

  • How do I get last 15 rows from a select query

    Hello,
    I am writing a query, and I need to filter the last 15 rows of from the select query.
    For example: Select id, name,join_date from emp order by join_date;
    So I need to get the last 15 rows from emp table so that we can who are the last 15 employees joined the organization. I want to show the result in ascending order, otherwise I would have taken first 15 rows with order by clause as descinding order.
    Thanks in advance,
    Param.

    SQL> select ename, join_date from test222
    2 where rownum < 6
    3 order by join_date
    4 /
    ENAME JOIN_DATE
    CNC5461177794 14-FEB-02
    OR91551178218 14-FEB-02
    TUB9894676495 14-FEB-02
    SG15431177117 14-FEB-02
    PIB9384674017 14-FEB-02
    SQL> SELECT * from
    2 (select ename, join_date from test222
    3 order by join_date desc)
    4 WHERE rownum < 6
    5 /
    ENAME JOIN_DATE
    II61111208401 19-MAR-02
    II61451208038 18-MAR-02
    PI20014184983 01-MAR-02
    BNF2221148037C 28-FEB-02
    UO78902581 18-FEB-02
    Can you see the problem now ?
    You can test this concept with your own table.
    have a good day,
    Sri

  • How to collect the deleted query in a transport request.

    Hi Friends,
    I have created a query and transported it to the Quality, the data content is all ok, except that i have not used the Project Naming conventions. Now i have a defect against my name for this. I have to copy the same query with the correct Naming convention and transport it.
    My question is after copying the query with correct name i have to delete the old query (if not there would be 2 versions of the same query). How do i collect the deleted image of the query in a transport and send it to quality?.
    I tried deleting a test query from Bex Designer, but this does not ask me for a transport. should i use RSZDELETE?. Not sure if it asks for a transport request when i delete the query.
    Can someone pls tell me how to go about this?.
    Thanks in advance.
    BN

    Hi BN,
      I do agree that deleting directly in Quality and Prod is not good way and not recommeded.
    I have not tried and deleted.But if the system is configured in such a way  that if it doesnt ask for a request
    then i feel you have no option.
    If any object is deleted then you must have the deletion image collected into request at the same point when you are deleting.Because later when we go to transport connection we wont find the object itself.
    What i think from your point as you said you have done earlier  is you must have any open request regrding this query and when this query is deleted , the deletion image is also included in the same request.
    So go to se03 and give your deleted query name and check all the requests.
    Check in the requests when the deletion image is captured or not. we might be knowing that this is cpatured.
    Regards
    vamsi
    Edited by: vamsi talluri on Nov 9, 2010 9:14 PM

Maybe you are looking for