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

Hello

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
         );
Who calculates a difference running and uses «row_number() over (...)» which is a specific feature of the Oracle to do it. We get the following result (that we will consider correct):
     EMPNO ENAME             SAL RUNNING_DIFF
---------- ---------- ---------- ------------
      7934 MILLER           1300         1300
      7782 CLARK            2450        -1150
      7839 KING             5000        -6150
I wanted to arrive at a different solution from the solution, it was not a specific Oracle . I tried the following code:

(EDIT: after further thought, this code is entirely different sense and will never get closer, the result above.) Considers that it is wrong and ignore this attempt.)
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        -8750
that is a long way from the initial result. I tried everything I could think to order lines before running difference is calculated, but were unsuccessful.

Is there a way to change this second request-(without using Oracle specific features) - without the help of windowing functions that give the same result as the first query?

Rephrase the question above:

Is it possible, using plain vanilla SQL (which is the aggregate functions and operations such as joins and unions) to create a query that produces the same result as the first?

In addition, it is not for production code. It's just an exercise in manipulation set I would like to see a solution for.

Thank you for your help,

John.

Published by: 440bx - 11 GR 2 on July 18, 2010 12:50 AM - correct ' ho w "to"how ".

Published by: 440bx - 11 GR 2 on July 18, 2010 01:42 - struck all references to row_number and windowing being features of Oracle functions.

Published by: 440bx - 11 GR 2 on July 18, 2010 03:51 - pointed out that my essay is terribly wrong and it had reaffirmed the goal to make it clearer.

Hi, John,.

A way to get a total operating (which is essentially what you want) must make a self-join. Join each line (let's call it the current line, or c) for himself and everything that preceded it (call this the previous line or p), and do a regular lump 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        -6150

I said you basically want a total runninng. There are two differences between a cumulative and your needs
(1) you want to have a total of the negation of what is in the table. That's trivial: use a sign less.
(2) you want the first point to count as positive rather than negative. It's not so trivial. The above query counts all know as negative, but adds an offset to make it appear as if the first item had been posted as a positive, not negative result.

You don't say what you want to do in the case of a tie (two or more lines having the same sal). The above query uses empno as a tiebreaker, so all sals are calculated as if they were separate. This is similar to what the analytical functions do when the window comes from the ranks. If you want something similar to windowing by scope, which could actually be simpler.

The above query calculates a running_diff separate for each deptno, similar to "PARTITION BY deptno" in analytic functions. You happen be interested in a single deptno right now, but you can change the WHERE clause of the main query, or to omit, and the query still works. If you don't want this feature (analagoud for not having any PARTITION BY), it is easy to change the query.

You can also get these results by using a WITH recursive clause. Which meets the criteria to avoid analytical functions and features specific to Oracle, but not on the use of the only clear and simple SQL features.

Tags: Database

Similar Questions

  • How to convert the hierarchical query of SQL Server (CTE) to Oracle?

    How to convert the hierarchical query of SQL Server (CTE) to Oracle?

    WITH cte (col1, col2) AS
    (
    SELECT col1, col2
    FROM dbo. [tb1]
    WHERE col1 = 12
    UNION ALL
    SELECT c.col1, c.col2
    FROM dbo. [tb1] AS c INNER JOIN cte AS p ON c.col2 = p.col1
    )
    DELETE one
    FROM dbo. [tb1] AS an INNER JOIN b cte
    ON a.col1 = b.col1

    Hello
    Something like this maybe:

    DELETE FROM dbo.tb1 a
     WHERE EXISTS (
      SELECT 1
        FROM dbo.tb1 b
      WHERE a.co11 = b.col1
          AND a.col2 = b.col2
       START WITH b.col1 = 12
      CONNECT BY b.col2 = PRIOR b.col1)
    

    Although you need to do here is to check that CONNECT it BY SELECT, returns records you wait first, then the DELETION should work too.

  • How to exclude records from the outer query

    My apologies if this was requested. I find no answer. I don't know what terminology should be for that matter.

    In simple terms, I want to use the custom in where clause to select records. Problem is function will fail if applied to old records, as there was no relevant data. I have logic to exclude old records, but the problem is that this process running function before old records are excluded. I tried an inside view to exclude records before their passage in the outer query, but this does not resolve the situation.

    Below shows high level required

    Select x

    tab

    where (condition to exclude the old records)

    and function (tab.y) = value

    If I rewrite as below, still have the problem. Was hoping to exclude former records apply before function.

    Select inn.x

    Of

    (select x,

    There

    tab

    where (condition to exclude the old records)) inn

    where function (inn.y) = value

    Thank you

    Hello

    Including ROWNUM in the result set of the query-void will force the subquery to do first:

    Select inn.x

    Of

    (select x,

    There,

    ROWNUM AS r

    tab

    where (condition to exclude the old records)

    ) inn

    where the function (inn.y) = some_value

    Since ROWNUM depends on the WHERE clause of the query-sup, the query cannot be rewritten to the main to do first query WHERE clause.

  • How to avoid the report query needs a unique key to identify each line

    Hello

    How to avoid the error below

    The report query needs a unique key to identify each row. The supplied key cannot be used for this query. Please change the report attributes to define a unique key column.

    I have master-detail tables but without constraints, when I created a query as dept, emp table he gave me above the error.

    Select d.deptno, e.ename

    by d, e emp dept

    where e.deptno = d.deptno

    Thank you and best regards,

    Ashish

    Hi mickael,.

    Work on interactive report?

    You must set the column link (in the attributes report) to something other than "link to display single line." You can set it to 'Exclude the column link' or 'target link to Custom.

  • Linux Server (how to record the out command has put on another file.)

    Hi all
    I have Q?
    How do to record the out command put in another file.

    Ex: #ps - ef
    This particular exit cmd I need to record another file.
    is it possible... If possible... Please let me know
    And how to record the history of orders under Linux.

    DF h > /oracle/output.log

    Oracle - name of the mount point

    Concerning
    Asif Kabir

  • How to get the sql query result?

    Hello

    Currently I use LV2012 to connect to an Oracle database server. After the Oracle Express and Oracle ODBC driver facilities/settings made.

    I managed to use the SQL command to query the data through my command prompt window.

    Now the problem is, how to do the same task in Labview using database connectivity tools?

    I have build a VI to query as being attached, but I have no idea of what range to use to get the result of the query.

    Please help me ~ ~

    Here is a piece of code that I use to test the SQL commands, you can use the part that retrieves the results of sql.

    It is also possible to get the rear column headers, but it's for the next lesson!

    ;-)

  • How to call the &lt; af:query &gt; Search feature by clicking on an image?

    Hi all

    I created a test named and I dragged on my page .jspx as "ADF with Table query Panel. I put the display as 'Simple' Mode in the Properties Inspector, who will hide all the default components of < af:query >. Now I use < af:commandImageLink >. My question is how can I call the < af:query > Search feature when the user clicks on an image? Any suggestion would be appreciated.

    Thank U...

    If you want to invoke af:query search by program button, follow these steps:

    1 Select af:query--> Advanced--> connections and bind it to the back bean

      
    

    2. in the .jspx add af:link like this:

    
              
    
    

    3 - runQuerySearchAction should be like this:

      public String runQuerySearchAction()
      {
        QueryDescriptor queryDescriptor = getRichQuery().getValue();
        QueryEvent queryEvent = new QueryEvent(getRichQuery(), queryDescriptor);
        queryEvent.setPhaseId(PhaseId.INVOKE_APPLICATION);
        getRichQuery().queueEvent(queryEvent);
        return null;
      }
    
  • How to wear the formhandler query parameter in jsp

    I know that its very stupid question, but I don't get a query parameter. I don't know what mistake I make.

    Here is my code snippet:

    I created a formhandler


    LoginFormHandler.java

    public boolean handleLogin (request, response DynamoHttpServletResponse DynamoHttpServletRequest)

    throws IOException, ServletException {}

    Here the value of the user ID is available I checked using DD

    request.setParameter ("userId", username);

    handleFlag = checkFormRedirect (getCreateSuccessURL (), getCreateFailureURL(), request, response);

    in CreateSuccessURL it redirects to LoginSuccess.jsp

    LoginSuccess.jsp

    < %

    DynamoHttpServletRequest drequest = ServletUtil.getDynamoRequest (request);

    % >

    value: < %=drequest.getParameter("userId") % >

    Once that LoginSuccess.jsp the display is showing the value null of userId

    Please let me know how to wear the setting the Manager of jsp.

    Application settings will be lost in the success page because the formhandler send a redirect to the success page.

    It will be new demand for the success page.

    As suggested, or you will need to put this in formhandler, or cookie or in the url

    Peace

    Shaik

  • How to get the inline query which is drawn from the TAB specific Application.

    Hi all I use 10.2.0.4.0 oracle version.

    I want to capture the sql that is raised in my prod database when an applicaton tab is hit as it takes about 5 minutes for the tab to be loaded. So is it possible, for the inline sql, which is the origin of the problem, directly from the prod environment.

    (Note: I looked through the browser session in PROD DB for the query, but there, I found a lot of meetings and a lot of requests, I do not know how to distinguish the session being created by the specific tab I hit).

    >

    Hello

    I want to capture the sql that is triggered to my database of prod
    When an applicaton tab is hit as it takes about 5 minutes so that the tab
    to be loaded. So is it possible to get the inline sql, which is
    the origin of the problem, directly from the prod environment.

    Please, please tell us that you have a Test environment? Log into that, then run a trace.
    No doubt you can either descend all test for a few miinutes and/or
    easily distinguish sessions on your Test System? That's exactly what the test
    the environments are for.

    The SQL execution will be the same - you can go try to find
    the root cause of the problem.

    HTH,

    Paul...

  • How to make the simple query for this scenario... ?

    Hello:

    Dummy table provided for simplicity.

    It's my database table (Table_A)

    Date1 | Plane1 | Category | Duration | Fees
    01/01/2011 | A | Gold | 5. 2
    01/01/2011 | C | Money | 4. 11
    01/01/2011 | B | Gold | 6. 2
    01/01/2011 | D | Gold | 2. 4
    01/01/2011 | B | Gold | 3. 5
    01/01/2011 | A | Money | 4. 8
    01/01/2011 | B | Gold | 1. 3

    I need to write a query to get the result below:

    Date1 | Plane1 | Sum_Duration | Sum_Charge | Sum_Gold_Duration | Sum_Gold_Charge | Sum_Silver_Duration | Sum_Silver_Charge
    01/01/2011 | A | 9. 10. 5. 2. 4. 8
    01/01/2011 | B | 10. 10. 10. 10. 0 | 0
    01/01/2011 | C | 4. 11. 0 | 0 | 4. 11
    01/01/2011 | D | 2. 4. 2. 4. 0 | 0

    This query will provide the 1st four columns:

    SELECT Date1,
    base1,
    Sum (Duration) Sum_Duration,
    Sum (load) Sum_Charge
    FROM TABLE_A
    GROUP BY date1, rarateplan

    But I need to know how to get the rest of the columns (i.e. Summary according to categories; from 5 to 8 columns)? Is this can be done in a single query without writing subqueries?

    Please let me know, (with code), the best way.

    Thank you-
    Tanvir

    Use like this:

    SELECT Date1,
    base1,
    Sum (Duration) Sum_Duration,
    Sum (load) Sum_Charge,
    SUM (decode(Category,'Gold',duration,0)) Sum_Gold_Duration,
    SUM (decode(Category,'Gold',charge,0)) Sum_Gold_charge,
    SUM (decode(Category,'Silver',duration,0)) Sum_Silver_Duration,
    SUM (decode(Category,'Silver',charge,0)) Sum_Silver_charge
    FROM TABLE_A
    GROUP BY date1, rarateplan

    Published by: SANT007 on August 11, 2011 11:04

  • How to write the select query for it

    Hello

    I had an html form and the area I drop down and he needs to select several values in the drop-down box. When I select multiple values then I have to write the query to SQL select statement.

    When I try to write the select statement and trying to run I get the error message.

    Select * from Table

    where emo_no = '1,2,3 '.

    That's how I write the query please suggest me how to write the query to select several values in the drop-down box.

    Thank you

    Use the keyword sql 'in '.  If you don't know how, I've heard good things about the book Teach Yourself SQL in 10 Minutes by Ben Forta.

  • How to optimize the select query executed in a cursor for loop?

    Hi friends,

    I run the code below and clocked at the same time for each line of code using DBMS_PROFILER.
    CREATE OR REPLACE PROCEDURE TEST
    AS
       p_file_id              NUMBER                                   := 151;
       v_shipper_ind          ah_item.shipper_ind%TYPE;
       v_sales_reserve_ind    ah_item.special_sales_reserve_ind%TYPE;
       v_location_indicator   ah_item.exe_location_ind%TYPE;
    
       CURSOR activity_c
       IS
          SELECT *
            FROM ah_activity_internal
           WHERE status_id = 30
             AND file_id = p_file_id;
    BEGIN
       DBMS_PROFILER.start_profiler ('TEST');
    
       FOR rec IN activity_c
       LOOP
          SELECT DISTINCT shipper_ind, special_sales_reserve_ind, exe_location_ind
                     INTO v_shipper_ind, v_sales_reserve_ind, v_location_indicator
                     FROM ah_item --464000 rows in this table
                    WHERE item_id_edw IN (
                             SELECT item_id_edw
                               FROM ah_item_xref --700000 rows in this table
                              WHERE item_code_cust = rec.item_code_cust
                                AND facility_num IN (
                                       SELECT facility_code
                                         FROM ah_chain_div_facility --17 rows in this table
                                        WHERE chain_id = ah_internal_data_pkg.get_chain_id (p_file_id)
                                          AND div_id = (SELECT div_id
                                                          FROM ah_div --8 rows in this table 
                                                         WHERE division = rec.division)));
       END LOOP;
    
       DBMS_PROFILER.stop_profiler;
    EXCEPTION
       WHEN NO_DATA_FOUND
       THEN
          NULL;
       WHEN TOO_MANY_ROWS
       THEN
          NULL;
    END TEST;
    The SELECT inside the LOOP FOR cursor query took 773 seconds.
    I tried to use COLLECT in BULK instead of a cursor for loop, but it did not help.
    When I took the select query separately and executed with a value of the sample, and then he gave the results in a Flash of a second.

    All tables have primary key index.
    Any ideas what can be done to make this code more efficient?

    Thank you
    Raj.
    DECLARE
      v_chain_id ah_chain_div_facility.chain_id%TYPE := ah_internal_data_pkg.get_chain_id (p_file_id);
    
      CURSOR cur_loop IS
      SELECT * -- better off explicitly specifying columns
      FROM ah_activity_internal aai,
      (SELECT DISTINCT aix.item_code_cust, ad.division, ai.shipper_ind, ai.special_sales_reserve_ind, ai.exe_location_ind
         INTO v_shipper_ind, v_sales_reserve_ind, v_location_indicator
         FROM ah_item ai, ah_item_xref aix, ah_chain_div_facility acdf, ah_div ad
        WHERE ai.item_id_edw = aix.item_id_edw
          AND aix.facility_num = acdf.facility_code
          AND acdf.chain_id = v_chain_id
          AND acdf.div_id = ad.div_id) d
      WHERE aai.status_id = 30
        AND aai.file_id = p_file_id
        AND d.item_code_cust = aai.item_code_cust
        AND d.division = aai.division;         
    
    BEGIN
      FOR rec IN cur_loop LOOP
        ... DO your stuff ...
      END LOOP;
    END;  
    

    Published by: Dave hemming on December 4, 2008 09:17

  • How to get the SQL query running of af: search?

    I use JDeveloper 11.1.2.3.0. I have a page where I've set up an af:query and an array of result. The problem is that I can't get the exact query that is used during the execution of this component in a managed bean method. Is it possible to get the query string that is run within the af: query?

    Thank you

    Hello

    Method of the ViewObject getQuery() returns what you need;

    You can replace the executeQueryForCollection(), and prior to calling super, you can print the result of getQuery() method:

    public void executeQueryForCollection (rowset Object,

    Object [] params,

    {int noUserParams)

    System.out.println ("SQL =" + getQuery());

    call the super method here...

    }

  • How to clear the search query result set

    I dropped a search with the table query. When I search a value it is the display of the result, but when I click on the reset button, only the query Panel is reset to zero and not the table. What can I do to reset the table component associated with the query?
    When I click on the reset button, only the query panel goes to zero and no table.

    It will be reset nt table.

    What can I do to reset the table component

    Use of the component range reset. to do so.

    http://jobinesh.blogspot.in/2009/10/reset-content-of-Web-page.html
    http://myadfnotebook.blogspot.in/2011/05/making-reset-button-in-afquery.html trickles you want
    http://andrejusb.blogspot.in/2009/09/programmatical-reset-for-query-results.html

    -edited lately

    Published by: ADF7 on February 22, 2012 12:58 AM

  • Error giving a subquery, but with the outer query, it gives no error.

    Hello
    The following query gives error "ORA-00979: not a GROUP BY expression" (I know to use the filter condition in the WHERE clause, but for reasons explaining the problem, I use the HAVING clause)

    SELECT DeptNo
    WCP
    HAVING comm IS NULL;

    But when I use it as a subquery in as long as below, the query will run successfully (resultset may be wrong).

    SELECT d.
    BY d Dept.
    (SELECT deptno
    WCP
    WITH comm IS NULL) a
    WHERE d.deptno = a.deptno;

    Please explain the reason.

    Kind regards
    Danish

    Sort of philosophical question. But you're right, this behavior can be misleading.

Maybe you are looking for