Can we use aggregate of 2 tables in a single query?

Hi people,

I have a query that goes like this:

Select
Items.1,
Items.2, etc.
Sum (Stock.1),
Sum (Orders.1)
Of
Items, Stock, orders
Where
Items.ID = Stock.ID - (1 to many relationship)
AND
Items.ID = Orders.ID - (1 to many relationship)
Group By
Items.1,
Items.2, etc.
Order by
Items.ID

The idea is that against every item in stock, I should get to total the current level of stocks and inventories of the element 'custom '. In case someone wandering stock are calculated by the movements of stock - in and out - so the "Sum (Stock.1)" is actually a compound essentially statement Sum (stock_In) - Sum (stock_out) (who normally works OK as below)

If I remove the ' table and the columns of the order, I get the right total stock - Sum (Stock.1)
However, the second adding 'Sum' on the table 'Orders' then the two sums give incorrect results (result of Cartesian type)
Similarly, leaving in the 'orders' and removing the 'Stocks' statements give the correct sum of the 'orders '.

So either I'm doing something wrong or does not have two functions aggreagte on different tables in SQL.

If we can not use 2 aggregates of separate tables in a simple SQL query, is there another way to make this request?

Thanks in anticipation!

Hello

When you have two (or more) a one-to-many relationship, you need to aggregate each in a separate query.
For example, you can aggregate the orders in a subquery (ordes_summary, below) and combine the stock in the main query, like this:

WITH     orders_summary     AS
(
     SELECT       id
     ,       SUM (col_1)     AS orders_total
     FROM       orders
     GROUP BY  id
)
SELECT       i.col_1
,       i.col_2
,       SUM (s.col_1)          AS stock_total
,       MAX (o.orders_total)     AS orders_total
FROM       items            i
,       stock            s
,       orders_summary  o
WHERE       i.id     = s.id
AND       i.id     = o.id
GROUP BY  i.col_1
,       i.col_2
ORDER BY  i.col_1
,       i.col_2
;

I hope that answers your question.
If this isn't the case, post some sample data and desired results based on these data, as suggested Anurag.

Tags: Database

Similar Questions

  • Can I use the data dictionary tables based on RLS policy?

    Hello guys, I use the package level security line to limit certain lines to some users.

    I created several roles, I want to just enable certain roles to see all the columns, but the other roles, I'm not that they see all the lines. I mean to do this I use the session_roles table data dictionary however it did not work.

    What to do in order to not allow rows of user roles?
    Can I use the data dictionary tables in RLS?


    Thank you very much.

    Polat says:
    What to do in order to not allow rows of user roles?
    Can I use the data dictionary tables in RLS?

    Ensure that:

    SQL> CREATE OR REPLACE
      2    FUNCTION no_sal_access(
      3                           p_owner IN VARCHAR2,
      4                           p_name IN VARCHAR2
      5                          )
      6      RETURN VARCHAR2 AS
      7      BEGIN
      8          RETURN '''NO_SAL_ACCESS'' NOT IN (SELECT * FROM SESSION_ROLES)';
      9  END;
     10  /
    
    Function created.
    
    SQL> BEGIN
      2    DBMS_RLS.ADD_POLICY (
      3                         object_schema         => 'scott',
      4                         object_name           => 'emp',
      5                         policy_name           => 'no_sal_access',
      6                         function_schema       => 'scott',
      7                         policy_function       => 'no_sal_access',
      8                         policy_type           => DBMS_RLS.STATIC,
      9                         sec_relevant_cols     => 'sal',
     10                         sec_relevant_cols_opt => DBMS_RLS.ALL_ROWS);
     11  END;
     12  /
    
    PL/SQL procedure successfully completed.
    
    SQL> GRANT EXECUTE ON no_sal_access TO PUBLIC
      2  /
    
    Grant succeeded.
    
    SQL> CREATE ROLE NO_SAL_ACCESS
      2  /
    
    Role created.
    
    SQL> GRANT SELECT ON EMP TO U1
      2  /
    
    Grant succeeded.
    
    SQL> CONNECT u1@orcl/u1
    Connected.
    SQL> select ename,sal FROM scott.emp
      2  /
    
    ENAME             SAL
    ---------- ----------
    SMITH             800
    ALLEN            1600
    WARD             1250
    JONES            2975
    MARTIN           1250
    BLAKE            2850
    CLARK            2450
    SCOTT            3000
    KING             5000
    TURNER           1500
    ADAMS            1100
    
    ENAME             SAL
    ---------- ----------
    JAMES             950
    FORD             3000
    MILLER           1300
    
    14 rows selected.
    
    SQL> connect scott@orcl
    Enter password: *****
    Connected.
    SQL> GRANT NO_SAL_ACCESS TO U1
      2  /
    
    Grant succeeded.
    
    SQL> connect u1@orcl/u1
    Connected.
    SQL> select ename,sal FROM scott.emp
      2  /
    
    ENAME             SAL
    ---------- ----------
    SMITH
    ALLEN
    WARD
    JONES
    MARTIN
    BLAKE
    CLARK
    SCOTT
    KING
    TURNER
    ADAMS
    
    ENAME             SAL
    ---------- ----------
    JAMES
    FORD
    MILLER
    
    14 rows selected.
    
    SQL> 
    

    SY.

  • What API can be used to update the table cs_estimate_details (repair)

    I need to update the columns 'pricing_context' and 'pricing_attribute1' in the cs_estimate_details table.

    Which API can be used to update the columns. Where can I update the table directly?

    Try to use this "CS_Charge_Details_PVT" which in turn call "CS_ESTIMATE_DETAILS_PKG".

  • can we use DIV instead of tables in the APEX

    Morning friends,

    can we use < div > instead of using tables in the APEX. If so, let me know da procedure. Please make me understand in layman's term, as I just started learing APEX.

    Greetings
    Jean francois

    As I said in the first line of my first post:

    Yes, you can. You must do this in page templates, region or report on shared components of the request of the manufacturer.

    If you look at, you'll see the models and all the table tags HTML. I would say that you copy a model at a time and work with your copy so that you don't the hose upward standard Apex stuff.

    Earl

    Published by: Earil on April 9, 2009 08:57

  • Insert two tables with a single query (same ID)

    Hello

    I want to insert two tables at the same time (with a single request) provided that both records get inserted with the same identifier. How can I do this?
    Table Movies
    id 
    name
    
    Table Category
    movie_id
    cat_type
    (a) insert in the first table, retrieve the id (can be using
    my_sequence.currval
    and then insert into another table.

    question: He brings three queries to the Database, I also suspect that when several people trying to insert there is a problem, I could be wrong.

    I have no other idea.

    Greatly appreciated!

    think you need to do as an anonymous pl/sql block.

    Dim cn As New OracleConnection("DataSource = xx'; user id = xx; password = xx;")
    
    Try
     'build the anonymous pl/sql
     Dim sb as New System.Text.StringBuilder
     sb.Append("declare")
     sb.Append(" l_N number;")
     sb.Append("begin")
     sb.Append("insert into movies (id,name) values (my_sequence.nextval, 'film1') returning id  into l_N;")
     sb.Append( "insert into category values (l_N, 'Category type');")
     sb.Append(" END;")
    
     'create commd object
    
     Dim cmd as New OracleCommand(sb.ToString,cn)
     cmd.Connection.Open()
     cmd.ExecuteNonQuerry()
     cmd.Connection.Close()
     cmd.dispose()
     Catch ex as Exception
    
      blah blah blah
    
    End try
    
      
    

    Published by: pollywog on May 28, 2010 10:48

    Published by: pollywog on May 28, 2010 10:49

  • Table names are stored in a separate table; How can I use the domain as table name?

    Dear Experts,

    My version of oracle is,

    Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production

    PL/SQL Release 9.2.0.1.0 - Production

    CORE 9.2.0.1.0-Production

    AMT for 32-bit Windows: Version 9.2.0.1.0 - Production

    NLSRTL Version 9.2.0.1.0 - Production

    I stored the table names in a separate table as

    Table name: all_table

    Fields are: table_id, table_name, desc

    record of the sample: 1, EMP, EMPLOYMENT DETAILS

    Now I want to select all the contents of a perticular table, his name is all_table.

    (ie)

    Select * from (select table_name from all_table where table_id = 1);

    But it is not listing the details of the EMP table.  Its poster simply the name of the field "EMP".

    Please help me in this regard.

    Hello

    Whenever you make dynamic SQL statements, you must place the dynamic whole statement in a single string variable.  When debugging, display this string before running it.  If you get a runtime error that will show you the statement he makes, which often made the obvious cause.  For example:

    DECLARE

    CURSOR c IS

    SELECT table_name

    From user_tables;

    CNT NUMBER;

    sql_txt VARCHAR2 (1000);

    BEGIN

    FOR ut IN t

    LOOP

    sql_txt: = 'SELECT COUNT (*).

    || « DE » ' || t.table_name | '"';

    dbms_output.put_line (sql_txt |) "= sql_txt"); -For debugging

    EXECUTE IMMEDIATE sql_txt INTO cnt;

    dbms_output.put_line (' Table: ')

    || t.table_name

    || ' ('

    || CNT

    || "lines)"

    );

    END LOOP;

    END;

    /

    You can comment the put_line extra call when you are convinced that sylvie statement works.

    If you have non-standard table names (for example, names that contain spaces) you must place the names of the tables in double - quotes, as I did above.

  • Can I use more than 1 layer in a single layer mask?

    Hi all!


    I am a beginner in Photoshop, so everything I do to this tent to complete the tutorials.


    At a given time of the lesson I started today, mentions of the description that I must make a selection in the left part of the image, add a layer mask and press Ctrl + Backspace to make the selection disappears. I did it, no problem.


    The next step is to do the same in the upper part of the image.


    My problem is that I already have an active layer mask and I can't repeat the same steps because I am not allowed by the program to create a second in the same layer.


    What Miss me?

    Its very easy really and you do not need more of a mask. The author would probably include a photo of the layers palette for orientation.

    I have not used a path to create the edges of the pieces of the puzzle here, but the principle is exactly the same.

    Hope that helps

    Terri

  • Using variables such as table names. Ideas for alternative designs

    Hello

    I am the design of an application that uses synonyms to pull information from the 'client' DBs via links from DB. Synonyms are created with a DB_ID in name (example: CUSTOMER_100, CUSTOMER_200... where the 100 and 200 are DB IDs of 2 separate DBs customer.)

    I have a procedure that selects data in the synonym based on what DB_ID is passed to the procedure. I want to be able to perform this procedure for any entered DB_ID. I know now I can't use variable for the table names names and using EXECUTE IMMEDIATE does not seem suitable for what I'm trying to do.

    Does anyone have suggestions or re-design options, I could use to achieve this generic procedure which will select a certain synonym based on the information of DB input parameters? Thank you.

    CREATE or REPLACE PROCEDURE CUSTOMER_TEST (p_host IN VARCHAR2, p_db_name IN VARCHAR2, p_schema in VARCHAR)

    IS

    v_hostname VARCHAR2 (50): = UPPER (p_host);

    v_instance VARCHAR2 (50): = UPPER (p_db_name);

    v_schema VARCHAR2 (50): = UPPER (p_schema);

    v_db_id NUMBER;

    v_synonym VARCHAR2 (50);

    CURSOR insert_customer

    IS

    SELECT

    c.customer_fname,

    c.customer_lname

    OF v_synonym_name c;

    BEGIN

    -MADE BASED ON INPUT PARAMETERS DB_ID

    Select d.db_id

    in v_db_id

    of t_mv_db_accounts ac.

    t_mv_db_instances I,.

    t_mv_dbs d,

    t_mv_hosts h

    where ac.db_ID = d.db_ID

    and i.db_ID = d.db_ID

    and i.HOST_ID = h.host_id

    and upper (H.HOST_NAME) = v_hostname

    and upper (D.DB_NAME) = v_instance

    and upper (Ac.ACCOUNT_NAME) = v_schema;

    -ADD DB_ID TO NAME SYNOYNM

    v_synonym: = 'CUSTOMER_ | v_db_id;

    FOR cust_rec IN insert_customer

    LOOP

    INSERT INTO CUSTOMER_RESULTS (First_Name, Last_Name)

    VALUES (cust_rec.customer_fname, cust_rec.customer_lname);

    END LOOP;

    COMMIT;

    END;

    /

    RGS,

    Rob

    EXECUTE IMMEDIATE ' INSERT IN CUSTOMER_RESULTS (First_Name, Last_Name) SELECT customer_fname, customer_lname FROM ' | v_synonym;

  • Can I use 'like' operator in the column virtaul

    Hello

    can I use as an operator in the column virtaul as below?
    or how can I use it?

    ----------------------------------------------------------------------------------------------------------------
    create table tab1
    (
    C_N_NUMBER VARCHAR2 (25).
    ACE RESET_STS (CASE C_N_NUMBER
    WHEN as 'RESET %' THEN 'NO RESET' OTHER END NULL) VIRTUAL
    ) ;

    ------------------------------------------------------------------------------------
    Rgds,
    PC

    Hello
    you, the correct syntax is

    create table tab1
    (
    C_N_NUMBER VARCHAR2 (25).
    ACE RESET_STS (CASE
    WHEN C_N_NUMBER like 'RESET %' THEN 'NO RESET' OTHER END NULL) VIRTUAL
    ) ;

    Jirka

  • Please I want to know can I use rich text editing like table, font... color in Thunderbird

    Please I want to know can I use rich text editing like table, font... color in Thunderbird

    Yes, you simply dial your email in HTML mode, which supports Thunderbird. If you search online you will find many, many guides on this topic.

    See you soon,.
    Dave

  • can I use Siri while Apple Watch is in mode of bedside table?

    Currently I have a led clock that projects the time on the Ceiling so that I don't have to look around to see what time it is, if I wake up early by mistake.  now that I have a Apple Watch mode night next to my bed stand, it would be cool to number ' Hey Siri, what time is "and get the time without opening my eyes!

    Is this possible? Apple Watch locks when it is not on my arm. Siri doesn't seem to be working while it is locked

    Hello

    No, it is not currently possible to use "Hey Siri" while Apple Watch is in bedside Mode (or Siri can be used in this mode by pressing the digital Crown).

    If you want to suggest that Apple consider adding support for Siri in Mode bedside table as a new feature, you can do so here:

    https://www.Apple.com/feedback/watch.html

  • Can change us line selected in ADF without using click to edit table feature.

    JDEV 12.1.3.0

    Hi Experts,

    Is there a way we can select a row in the table and click the button change the Panel collection. While the row becomes editable.

    Whatever row, we select and click on the edit button. This line becomes editable thattime only. Otherwise always disabled.

    Without using click to modify the ADF table feature.

    Thank you

    AR

    I had similar usecase

    Maybe you can tweek this blog to meet your needs

    Born in DeBug: press the Edit button to make editable line Table.

  • Why I can't use the nested aggregate function?

    Hello Experts,

    Why I can't use the nested aggregate function? There is not an ora-00979 group by error of expression.

    Oracle Database 11 g Release 11.2.0.4.0 - 64 bit Production

    Select

       SUM (BOX WHEN (KSD_CREATEDATE BETWEEN TRUNC((KSD_CREATEDATE)) AND TRUNC(MIN(KSD_CREATEDATE)) +60) THEN 1  ELSE 0 END) AS col

    DE TABLE_3_4

    GROUP BY STC_FIRMANO

    Thank you

    GROUP BY will manage the SUM function, but the MIN is used incorrectly - use another SELECTION to get it, or work with only with a single line. Otherwise, you could do WITH... get the SUM of SELECT MIN...

  • Please how can I use a value in a table of the adf in an actionListener to a button I created in a popup and thanks

    Please how can I use a value in a table of the adf in an actionListener to a button I created in a popup and thanks

    What is your version of JDev?

    Actually your question is not clear to me, but as I understand, it is you the table in the page and you have popup inside this popup you have the button you need when you click on the button to read the value of the selected table row. In the listener action button, so if you can get the current row of the table and after that you can get any attribute of the line as:

    DCIteratorBinding iter = (DCIteratorBinding) BindingContext.getCurrent().getCurrentBindingsEntry().get("TableIteratorName"); // from pageDef.
    Row r = iter.getCurrentRow();
    Object value1 = r.getAttribute("attribute1");
    Object value2 = r.getAttribute("attribute2");
    
  • How can I use statistics for all the tables in a schema in SQL Developer? and how long will it take on average?

    Hello

    How can I use statistics for all the tables in a schema in SQL Developer? and how long will it take on average?

    Thank you

    Jay.

    Select the connection and right-click on it and select schema statistics collection

Maybe you are looking for

  • about 2 years extended warranty

    Dear Sir I bought a new laptop in Pavilion 15 29 March 2014.i had already registered the product for extended warranty. I want to know the amount of the project application and it must be issued on the name of?

  • Software HP Deskjet 960C

    I recently bought a new computer for my wife.  The OS is Windows 7 Professional.  The printer is a HP deskjet 960C printer.  I can't seem to find the records of installadiotn to the printer and the HP site seems to say that there are no downloadable

  • OC C2D 3.0

    Hello, I have Dell 760 with socket 775, my first question is, can I upgrade my c2d four hearts? Model 0M858N-motherboard, chipset, q43/q45, A16 bios version. My second question is, can I have overclocked intel e8400, because my Bios is not classic, I

  • How to reset the BIOS pw?

    I can't get into my BIOS, I think I have a malware that has changed.  My computer does not open OS after that AVG has kits root and asked to reset.

  • All on my Server BES blackBerry Smartphones Blackberry devices use my internal ISP connection for Internet

    Hello I'm trying to understand why all BlackBerry in my company who are on my BES v4.5 using my internal Internet connection and not Verizon's Internet connection. Anyone have any ideas? This supposd to be this way?