ORACLE SQL Query with Parent and Child structure

I have 2 tables which are Account tbl and Customer tbl, the structure is like below:
Account tbl
Customer_ID    Account_ID    Parent_Account_ID    
3780952        3780952         3780952
3780997        3780997         3780997
3781004        3781004         3780997
Customer tbl (Customer_Group have different value, but im only interest on Personal)
Customer_ID      Customer_Group
3781004          Personal
3780997          Personal
3780952          PersonalThe rule to determine PS/NonPS, Principle, Supp as per below:
**PS/NonPs**
Customer_ID equal to Parent_Account and Parent_Account is unique (not exist more than 1)  then NonPs.
Customer_ID equal to Parent_Account and Parent_Account is non unique OR -   Customer_ID is not equal to Parent_Account then PS    
**Principle**  IF NonPS then Principle is Null IF PS - If Customer_ID equal to Parent_Account then Principle is Y else N
**Supp** IF NonPS then Supp is Null IF PS - If Customer_ID not equal to Parent_Account then supp is Y else N The final output should be like this
Customer_ID    Account_ID    Parent_Account_ID   PS/NonPS   Principle   Supp
3780952        3780952       3780952             NonPS       Null        Null
3780997        3780997       3780997             PS          Y           N
3781004        3781004       3780997             PS          N           Y I alredy tried many times but still cant get the output..anyone can help ?

hi,
i hope this is what you want , this query matches all of your mentioned requirements .
WITH accounts AS
     (SELECT 3780952 AS customer_id, 3780952 AS account_id,
             3780952 AS parent_account_id
        FROM DUAL
      UNION ALL
      SELECT 3780997 AS customer_id, 3780997 AS account_id,
             3780997 AS parent_account_id
        FROM DUAL
      UNION ALL
      SELECT 3781004 AS customer_id, 3781004 AS account_id,
             3780997 AS parent_account_id
        FROM DUAL),
     customer AS
     (SELECT 3781004 AS customer_id, 'Personal' AS customer_group
        FROM DUAL
      UNION ALL
      SELECT 3780997 AS customer_id, 'Personal' AS customer_group
        FROM DUAL
      UNION ALL
      SELECT 3780952 AS customer_id, 'Personal' AS customer_group
        FROM DUAL)
SELECT customer_id, account_id, parent_account_id, "PS/NonPS",
       CASE
          WHEN "PS/NonPS" = 'NonPS'
             THEN NULL
          WHEN customer_id = parent_account_id
             THEN 'Y'
          WHEN customer_id <> parent_account_id
             THEN 'N'
       END principle,
       CASE
          WHEN "PS/NonPS" = 'NonPS'
             THEN NULL
          WHEN "PS/NonPS" = 'PS' AND customer_id <> parent_account_id
             THEN 'Y'
          WHEN "PS/NonPS" = 'PS' AND customer_id = parent_account_id
             THEN 'N'
       END SUM
  FROM (SELECT   t1.customer_id, t1.account_id, t1.parent_account_id,
                 CASE
                    WHEN t1.customer_id = t1.parent_account_id
                    AND (SELECT COUNT (*)
                           FROM accounts
                          WHERE parent_account_id = t1.parent_account_id) = 1
                       THEN 'NonPS'
                    ELSE 'PS'
                 END "PS/NonPS"
            FROM accounts t1, customer t2
           WHERE t1.customer_id = t2.customer_id
        ORDER BY t1.customer_id)
output
CUSTOMER_ID     ACCOUNT_ID     PARENT_ACCOUNT_ID     PS/NonPS     PRINCIPLE     SUM
3780952     3780952     3780952     NonPS          
3780997     3780997     3780997     PS     Y     N
3781004     3781004     3780997     PS     N     YThanks,
P Prakash
Edited by: prakash on Jan 17, 2012 3:38 AM

Similar Messages

  • Session expiration issue with parent and child window

    Hi,
    We have two applications (App1 - Implemented using JSF, Spring and Hibernate and App2 -Implemented using Spring MVC, Spring JDBC).
    I have implemented 'Test Access Content' functionality in App1.
    First admin user (Role- Manager) needs to login to App1
    As part of 'Test Access Content' functionality, he enters URL with encrypted key and click 'Test Access' button.
    It opens new window (implemented using java script - window.open) and hits spring controller of App2.
    In spring controller of App2, I am decrypting the key to get user details. After that i am setting user details in session, constructing final URL to display actual content.
    Problem is parent window maintains session till child window renders response. Once child window renders response, parent window loosing session.
    So, if i click any button in parent window after child window renders response, it displays login page as there is no session for parent window.
    Please note that App1 and App2 are sharing same domain. only context paths are different for both apps (app1 and app2).
    Any suggestions on this issue are much appreciated. Please let us know if you have any questions.

    Hi,
    When you open a child window from parent window then you can access child data in the parent window through javascript.
    We have a main web page. There are quite many links on it from which >user can open new web pages but the data is saved when the submit >button on the main page is clicked. Also data that user entered on the >other sub pages is not displayed in the main window.
    1 is this a case of parent and child window.case 1 When you are submitting the main page you need to run javascript function and get data from child windows and save that to database or session. next time when you are displaying the main window you need to query session or database to display the child window data in the main window.
    Case 2> closing child window and you need data in the parent. This can be done in two ways.
    1> When you are closing the child window populate some variables of the main window using javasript.
    2> Save the values in the database or session and refresh the main window and extract data from database or session
    Where should the data be saved that user enetered on the sub pages as the data is not shown in the main page - should it be stored in the session?It is design decision. You can store data in either session or database when you are closing the child window. But ifyou are saving the data on the main page then you can populate main page with child windows data using javascript. Save the data t database when main window data is saved. Depends on business requirements.
    In short if you are saving child windows data in session or database then you need to refresh main screen to pull that data otherwise populate main screen using javascript.
    I hope i answered your questions :) best of luck

  • Need query linking parent and child discrete jobs created through ascp planning

    Could you help me create a query that will show both the parent and child discrete jobs created through ascp run? I do not need entire query. I need to know the names of tables and understand the links or joins between tables. Then, I shall be able to write the sql on my own.
    Thanks

    Just use a format like this:
    http://<Server Name>:<port Number>/OpenDocument/opendoc/openDocument.jsp?sDocName=reportB&sType=wid&sRefresh=Y
    &lsMObjectName=[test1],[test2]
    Here in lsM[ObjectName] parameter [ObjectName] = the object name which you want to send data to ReportB
    I can give you a idea of creating hyperlink for jumping another report (Here ReportB)
    Just use  a formula like that in any cell:
    ="<a href=http://<Server Name>:<port Number>/OpenDocument/opendoc/openDocument.jsp?sDocName=reportB&sType=wid&sRefresh=Y&lsMObjectName=[test1],[test2]&sWIndow=New> Click here to view </a>
    Now from the property select Read cell content as "Hyperlink"...
    thats it......
    For more information please see the
    "OpenDocument" artile
    Hope you can  get help from this
    Edited by: Arif Arifuzzaman on Aug 20, 2009 7:24 AM

  • SQL query with JSP and WML-parameters

    Hey,
    Could you help me?
    I'm trying to do the following. WML deck card 1 send parameter to same WML deck's card help. I try to read the parameter with JSP in card help by putting the parameter to SQL query, but it doesn't work. I can read the parameter with WML in card help. I can also print the value of the parameter with JSP if I generate WML with JSP.
    /*parameter sending from card 1 to card help*/
    out.println("<go href='#helpcard'>");
    out.println("<setvar name='valittukurssi' value='$(valittukurssi)'/>");
    /*parameter read with WML in card help */
    <p>Valitse kurssi.
    $valittukurssi</p>
    /'parameter read with JSP by generating WML with JSP*/
    out.println("<p>$valittukurssi</p>");
    /* SQL query with JSP */
    ResultSet uudettulokset = uusilause.executeQuery("select * from kurssi where lyhenne='$valittukurssi'");
    Thanks,
    Rampe

    You're problem is easy to fix. You're confusing WML variables with JSP variables. See below:
    >
    /*parameter sending from card 1 to card help*/
    out.println("<go href='#helpcard'>");
    out.println("<setvar name='valittukurssi'
    value='$(valittukurssi)'/>");
    Above you set a var that will work on the phone, not in JSP.
    /*parameter read with WML in card help */
    <p>Valitse kurssi.
    $valittukurssi</p>
    Yes the above does display the parameter, because it is a client side WML var, but you cannot use this variable in the JSP code (that's why your SWL fails).
    /'parameter read with JSP by generating WML with
    JSP*/
    out.println("<p>$valittukurssi</p>");Here's you're problem, the above line is EXACTLY the same as the one before it. When the container parses through this JSP code it translates the above line to:
    <p>$valittukurssi</p> on the WML page and the CLIENT uses it's local variable to display it.
    What you need and want is to have a variable that can be used in JSP code and output to your WML page. Here's how it's done:
    out.println("<go href='#helpcard'>");
    String some_name = "valittukurssi";
    out.println("<setvar name='"+some_name+"'
    value='$("+some_name+")'/>");
    //note that you may have to escape the ( and ) with a \
    //so we displayed the variable above into the WML page, now we can use it in the SQL query:
    /* SQL query with JSP */
    ResultSet uudettulokset =
    uusilause.executeQuery("select * from kurssi where
    lyhenne='"+some_name+"'");//the end of the command is: " ' " ) ;
    Frank Krul
    Got Node?

  • Sql query with conditions and calculations???

    Hi,
    how I can build a query with conditions and calculations?
    E.g. I've got this table
    Start          | End     |     Working Place     |     Mandatory
    01-JAN-13 | 11-JAN-13 |     Office           |          1
    14-JAN-13 | 25-JAN-13 |     Home Office      |     0
    04-MRZ-13| 15-MRZ-13 |     Office           |          0
    11-FEB-13 | 22-FEB-13 |     Office           |          1
    Now if column working place=Office and column mandatory=0
    the new column "price" has to calculate: (End-Start)* $25.00
    and if working place=Office and column mandatory=1
    the "price" column has to calculate: (End-Start)* $20.60
    else $0.00
    I tried it with the case statement but I didn't know how
    to calculate my values and display it to the virtual column "price".
    Something like
    case
    when Working_Place = 'Office' and Mandatory=1
         then ...
    else '0.00'
    end as PRICE
    Or is it not possible?
    Edited by: DB2000 on 12.03.2013 05:09

    Use CASE:
    select  start_dt,
            end_dt,
            working_place,
            mandatory,
            case
              when working_place = 'Office' and mandatory = 0 then (end_dt - start_dt) * 25
              when working_place = 'Office' and mandatory = 1 then (end_dt - start_dt) * 20.60
              else 0
            end price
      from  tbl
    START_DT  END_DT    WORKING_PLA  MANDATORY      PRICE
    01-JAN-13 11-JAN-13 Office               1        206
    14-JAN-13 25-JAN-13 Home Office          0          0
    04-MAR-13 15-MAR-13 Office               0        275
    11-FEB-13 22-FEB-13 Office               1      226.6
    SQL> SY.

  • Tuning SQL query with SDO and Contains?

    I'trying to optimize a query
    with a sdo_filter and an intermedia_contains
    on a 3.000.000 records table,
    the query look like this
    SELECT COUNT(*) FROM professionnel WHERE mdsys.sdo_filter(professionnel.coor_cart,mdsys.sdo_geometry(2003, null, null,mdsys.sdo_elem_info_array(1,1003,4),mdsys.sdo_ordinate_array(809990,2087279,778784,2087279,794387,2102882)),'querytype=window') = 'TRUE' AND professionnel.code_rubr ='12 3 30' AND CONTAINS(professionnel.Ctx,'PLOMBERIE within Nom and ( RUE within Adresse1 )',1)>0
    and it takes 15s on a bi 750 pentium III with
    1.5Go of memory running under 8.1.6 linux.
    What can i do to improve this query time?
    null

    Hi Vincent,
    We have patches for Oracle 8.1.6 Spatial
    on NT and Solaris.
    These patches include bug fixes and
    performance enhancements.
    We are in the process of making these patches
    avaialble in a permanent place, but until then, I will temporarily put the patches on:
    ftp://oracle-ftp.oracle.com/
    Log in as anonymous and use your email for
    password.
    The patches are in /tmp/outgoing in:
    NT816-000706.zip - NT patch
    libordsdo.tar - Solaris patch
    I recommend doing some analysis on
    individual pieces of the query.
    i.e. time the following:
    1)
    SELECT COUNT(*)
    FROM professionnel
    WHERE mdsys.sdo_filter(
    professionnel.coor_cart,
    mdsys.sdo_geometry(
    2003, null, null,
    mdsys.sdo_elem_info_array(1,1003,4),
    mdsys.sdo_ordinate_array(
    809990,2087279,
    778784,2087279,
    794387,2102882)),
    'querytype=window') = 'TRUE';
    2)
    SELECT COUNT(*)
    FROM professionnel
    WHERE CONTAINS(professionnel.Ctx,
    'PLOMBERIE within Nom and ( RUE within Adresse1)',1) >0;
    You might want to try reorganizing the entire
    query as follows (no promises).
    If you contact me directly, I can try to
    help to further tune the SQL.
    Hope this helps. Thanks.
    Dan
    select count(*)
    FROM
    (SELECT /*+ no_merge */ rowid
    FROM professionnel
    WHERE mdsys.sdo_filter(
    professionnel.coor_cart,
    mdsys.sdo_geometry(
    2003, null, null,
    mdsys.sdo_elem_info_array(1,1003,4),
    mdsys.sdo_ordinate_array(809990,2087279,
    778784,2087279,
    794387,2102882)),
    'querytype=window') = 'TRUE'
    ) a,
    (SELECT /*+ no_merge */ rowid
    FROM professionnel
    WHERE CONTAINS(professionnel.Ctx,
    'PLOMBERIE within Nom and
    ( RUE within Adresse1)',1) >0
    ) b
    where a.rowid = b.rowid
    and professionnel.code_rubr ='12 3 30';
    **NOTE** Try this with no index on code_rubr
    null

  • How to build a query across parent and child object fields?

    As a part of an Integration Requirement, I need to query Opportunity records that have been Modified after a specific date and time?
    Now, Opportunity has a child object called ProductRevenue with a one to many relationship. Is there anyway I can construct a querypage that will fetch records whose Opportunity fields 'OR' its child ProductRevenue's fields have been modified after a specific date and time?
    I have tried using the SearchSpec argument, but it does not let me query across child object fields.
    For eg:-
    ObjOpptyQueryPageInput.ListOfOpportunity.Opportunity.searchspec = "([ModifiedDate] > '01/01/2013 00:00:00') OR ([ProductRevenueData.ModifiedDate] >= '01/01/2013 00:00:00')";
    [This above code written in C# thew me an error saying - The object Opportunity does not have an integration component called - ProductRevenueData.ModifiedDate.]
    Any help will be greatly appreciated. Thank you.

    Hi,
    As far as I know this can't be done at once because you have to consider :
    - Every Opportunity and their time-limited ProductRevenues
    AND
    - Time-limited Opportunities
    If you want to achieve this, you have to consider the 2 datasets separately and make your first query :
    ObjOpptyQueryPageInput.ListOfOpportunity.Opportunity.searchspec = "([ModifiedDate] >= '01/01/2013 00:00:00')";
    but also another query with the restriction on the ProductRevenue Searchspec.
    This shouldn't be too hard because the searchspec functionality is present at each level :
    - ListOfOpportunity -> Opportunity (the top-level that you used for your query)
    - ListOfOpportunity -> Opportunity -> ListOfProductRevenue -> ProductRevenue (the sub-level that you should use for the second query)
    Then in your C# code, you merge the 2 datasets and you end up with your expected result.
    Hope this helps,
    Charles.
    http://www.dubant.com

  • Optimistic Lock with Parent and Child relationships

    Hi,
    I just have a question regarding optimistic locking. We have a scenario
    where a parent object has many child objects. Both the parent and the
    child objects have a jdolockx column in the database/jdo file.
    It appears that whenever you add a new child to the parent the parent's
    optimistic lock counter is also updated.
    eg
    parent.getChildren().add(child);
    child.setParent(parent);
    Why does this occur? There is no change made to the database table for
    the parent, except for the jdolockx column. Is there something that I can
    do to stop the lock count from incrementing when I child is added?
    We have a scenario where we have many threads of execution wishing to add
    children to a single parent. The parent itself isnt modified but this
    operation fails due to the parent lock counter being incremented.
    Any help would be appreciated
    Thanks
    Luke

    There is state image indicator in Kodo 3 which has more locking options
    beyond a simple number:
    http://solarmetric.com/Software/Documentation/3.0.1/docs/ref_guide_mapping_versionind.html#state-image
    In addition, you can plug your own version indicator.
    Our default optimistic locking avoids the problem of users having no
    idea what is -actually- in the collection/set at any given time.
    Inconsistencies can occur at the datastore level (user 1 adds
    object a to collection, user 2 removes a, user 1 adds object b... which
    should actually be in the DB? {a,b} or or {a}? This is one of the
    many ways in which not tracking changes to a collection/set can be
    hazardous).
    On locking exceptions, errors could be handled in some appropriate
    function (i.e. refresh, re-apply changes if applicable/safe,
    and commit).
    Luke wrote:
    Hi,
    I just have a question regarding optimistic locking. We have a scenario
    where a parent object has many child objects. Both the parent and the
    child objects have a jdolockx column in the database/jdo file.
    It appears that whenever you add a new child to the parent the parent's
    optimistic lock counter is also updated.
    eg
    parent.getChildren().add(child);
    child.setParent(parent);
    Why does this occur? There is no change made to the database table for
    the parent, except for the jdolockx column. Is there something that I can
    do to stop the lock count from incrementing when I child is added?
    We have a scenario where we have many threads of execution wishing to add
    children to a single parent. The parent itself isnt modified but this
    operation fails due to the parent lock counter being incremented.
    Any help would be appreciated
    Thanks
    Luke
    Steve Kim
    [email protected]
    SolarMetric Inc.
    http://www.solarmetric.com

  • Please, help me with parents and childs

    hi,
    I just can't figure it out which mc is the parent and which
    are its children. Please help.
    Here's the code:

    THX. I saw the same "family tree", but I started to doubt as
    soon as I tried to add blur filter to menu items. I've found it on
    the www.kirupa.com (they have some great stuff there). Here is the
    direct
    LINK
    to the script. Can you tell me, how can I add a blur filter to menu
    items. By default they are blured and OnRollover they get cleared.
    regards

  • SQL Query with Distinct and Count is wrong.

    Hello,
    i have another problem with a query.
    Here the Data:
    Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
    CREATE      TABLE      TABLE_1
    (       "ORDER_NR"        VARCHAR2 (12)
    ,        "PRIORITY"        VARCHAR2 (2)
    ,        "WO_STATUS"        VARCHAR2 (1)
    ,        "STATUS_DATE"        DATE
    ,       "ART_NR"                      VARCHAR2 (9)
    ,       "DESCRIPTION"      VARCHAR2 (255)
    ,                 "PRICE"                     VARCHAR2 (10)
    CREATE      TABLE      TABLE_2
    (     "ART_NR"            VARCHAR(9)
    ,     "MODELL"              VARCHAR2(10)
    ,     "MANUFACT"         VARCHAR2(20)
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300612',     '12',     'U',        TO_DATE('05-FEB-13 10:22:39','DD-MON-RR HH24:MI:SS'),     '005231987',     '1ST ANNUAL SERVICE',   '5000.2546');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300638',     '05',     'U',        TO_DATE('05-FEB-13 11:38:39','DD-MON-RR HH24:MI:SS'),     '005667821',     '3RD ANNUAL SERVICE',   '5269.7856');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300638',     '12',     'U',        TO_DATE('06-FEB-13 12:38:39','DD-MON-RR HH24:MI:SS'),     '005667821',     '1ST BIENNIAL SERVICE', '1234.4468');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300638',     '12',     'U',        TO_DATE('07-FEB-13 13:38:39','DD-MON-RR HH24:MI:SS'),     '005667821',     '3RD ANNUAL SERVICE',   '4366.7856');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300762',     '12',     'U',        TO_DATE('22-FEB-13 14:55:48','DD-MON-RR HH24:MI:SS'),     '018743356',     '3RD ANNUAL SERVICE',   '4462.8632');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300766',     '12',     'U',        TO_DATE('22-FEB-13 08:32:13','DD-MON-RR HH24:MI:SS'),     '018743356',     '2ND ANNUAL SERVICE',   '8762.6643');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300766',     '05',     'U',        TO_DATE('23-FEB-13 12:32:13','DD-MON-RR HH24:MI:SS'),     '018743356',     '1ST BIENNIAL SERVICE', '3425.6643');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300766',     '12',     'U',        TO_DATE('24-FEB-13 14:32:13','DD-MON-RR HH24:MI:SS'),     '018743356',     '2ND BIENNIAL SERVICE', '6678.6643');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300612',     '12',     'U',        TO_DATE('06-FEB-13 10:22:39','DD-MON-RR HH24:MI:SS'),     '005231987',     '1ST ANNUAL SERVICE',   '5000.2546');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300638',     '05',     'U',        TO_DATE('05-FEB-13 11:38:39','DD-MON-RR HH24:MI:SS'),     '005667821',     '3RD ANNUAL SERVICE',   '5269.7856');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300638',     '12',     'U',        TO_DATE('06-FEB-13 12:38:39','DD-MON-RR HH24:MI:SS'),     '005667821',     '1ST BIENNIAL SERVICE', '1234.4468');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300638',     '12',     'U',        TO_DATE('07-FEB-13 13:38:39','DD-MON-RR HH24:MI:SS'),     '005667821',     '3RD ANNUAL SERVICE',   '4366.7856');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300762',     '12',     'U',        TO_DATE('22-FEB-13 14:55:48','DD-MON-RR HH24:MI:SS'),     '018743356',     '3RD ANNUAL SERVICE',   '4462.8632');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300766',     '12',     'U',        TO_DATE('22-FEB-13 08:32:13','DD-MON-RR HH24:MI:SS'),     '018743356',     '2ND ANNUAL SERVICE',   '8762.6643');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300766',     '05',     'U',        TO_DATE('23-FEB-13 12:32:13','DD-MON-RR HH24:MI:SS'),     '018743356',     '1ST BIENNIAL SERVICE', '3425.6643');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300766',     '12',     'U',        TO_DATE('24-FEB-13 14:32:13','DD-MON-RR HH24:MI:SS'),     '018743356',     '2ND BIENNIAL SERVICE', '6678.6643');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005231987',     'X-RAY1',          'MANUFACT1');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005231987',     'X-RAY1',          'MANUFACT2');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005231987',     'X-RAY1',          'MANUFACT3');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005231987',     'X-RAY1',          'MANUFACT4');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005231987',     'X-RAY1',          'MANUFACT5');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005231987',     'X-RAY1',          'MANUFACT6');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005667821',     'LASER',          'MANUFACT1');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005667821',     'LASER',          'MANUFACT2');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005667821',     'LASER',          'MANUFACT3');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005667821',     'LASER',          'MANUFACT4');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('018743356',     'VACCUM',          'MANUFACT1');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('018743356',     'VACCUM',          'MANUFACT2');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('018743356',     'VACCUM',          'MANUFACT3');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('018743356',     'VACCUM',          'MANUFACT4');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('018743356',     'VACCUM',          'MANUFACT5');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('018743356',     'VACCUM',          'MANUFACT6');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005231987',     'X-RAY1',          'MANUFACT1');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005231987',     'X-RAY1',          'MANUFACT2');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005231987',     'X-RAY1',          'MANUFACT3');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005231987',     'X-RAY1',          'MANUFACT4');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005231987',     'X-RAY1',          'MANUFACT5');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005231987',     'X-RAY1',          'MANUFACT6');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005667821',     'LASER',          'MANUFACT1');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005667821',     'LASER',          'MANUFACT2');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005667821',     'LASER',          'MANUFACT3');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005667821',     'LASER',          'MANUFACT4');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('018743356',     'VACCUM',          'MANUFACT1');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('018743356',     'VACCUM',          'MANUFACT2');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('018743356',     'VACCUM',          'MANUFACT3');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('018743356',     'VACCUM',          'MANUFACT4');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('018743356',     'VACCUM',          'MANUFACT5');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('018743356',     'VACCUM',          'MANUFACT6');
    COMMIT;And my query:
    SELECT T1.ART_NR
    , T2.MODELL
    , SUM(ROUND(T1.PRICE, 2)) AS TOTAL_PRICE
    , COUNT(*) AS QTY
    , TO_CHAR(T1.STATUS_DATE, 'MON-RR') AS MONTH
    FROM TABLE_1 T1, TABLE_2 T2
    WHERE T1.WO_STATUS = 'U'
    AND T1.ART_NR = T2.ART_NR
    AND TO_CHAR(T1.STATUS_DATE, 'MON-RR') = 'FEB-13'
    GROUP BY T2.MODELL
    , T1.ART_NR
    , TO_CHAR(T1.STATUS_DATE, 'MON-RR')And the result:
    ART_NR      MODELL     TOTAL_PRICE        QTY     MONTH
    018743356 VACCUM     559916.16            96        FEB-13
    005667821 LASER        173936.48            48        FEB-13
    005231987 X-RAY1          120006             24        FEB-13My problem now is, the OTY field ist wrong it should count how often the equipment was in service in FEB-13 and group it by "MODELL" the MANUFACT field is not interesting for me, but this ist my problem, one Modell can have multible Manufacter and so i got a wrong count for my QTY.
    The next step i need is to group the result also by Service type (annual or biennial), like this:
    ART_NR      MODELL     TOTAL_PRICE        QTY     MONTH   SERVICE_TYPE
    018743356 VACCUM      1234.56               4         FEB-13     ANNUAL
    018743356 VACCUM      4423.48               10       FEB-13     BIENNIAL
    005667821 LASER         4783.11               2         FEB-13     ANNUAL
    005667821 LASER         1123.77               22       FEB-13      BIENNIAL
    005231987 X-RAY1        8966.12               6        FEB-13      ANNUAL
    005231987 X-RAY1        7826.44              12        FEB-13      BIENNIALThis values are only out of my head, not the table, only to show what i need.
    Thanks for your help.
    Greets Reinhard

    Hi,
    Here's one way:
    WITH    got_groups  AS
         SELECT  art_nr
         ,     TRUNC (status_date, 'MONTH')     AS month
         ,     CASE
                  WHEN  UPPER (description) LIKE '%ANNUAL%'
                                         THEN  'ANNUAL'
                  WHEN  UPPER (description) LIKE '%BIENNIAL%'
                                         THEN  'BIENNIAL'
              END                    AS service_type
         ,     TO_NUMBER (price)          AS price
         FROM     table_1
         WHERE     status_date     >= DATE '2013-02-01'
         AND     status_date     <  DATE '2013-03-01'
    ,       table_2_summary  AS
         SELECT DISTINCT       art_nr, modell
         FROM               table_2
    SELECT       g.art_nr
    ,       s.modell
    ,       ROUND ( SUM (g.price)
              , 2
              )          AS total_price
    ,       COUNT (*)          AS qty
    ,       g.month
    ,       service_type
    FROM       got_groups       g
    JOIN       table_2_summary  s     ON  s.art_nr  = g.art_nr 
    GROUP BY  g.art_nr
    ,            s.modell
    ,            g.month
    ,       g.service_type
    ;The reason why your aggregates were originally too high is that you have a many-to-many relationship between the tables. The tables are related only by art_nr, but art_nr is not unique in either table. Look at art_nr '005231987', example. There ate 2 rows in table_1 with that art_nr, and 6 rows in table_2 with the same art_nr. If we join on art_nr, then both of the rows in table_1 will match each of the 6 rows in table_2, so the COUNT will be 2 * 6 = 12, and in the SUM, each of the numbers from table_1 will get added 6 times.
    Why is table_2 designed the way it is? Cn there be multiple modells for the same art_nr? If so, what would you want for output? If there can only be 1 modell for each art_nr, then a better design would be to have a table that just had one row per art_nr, and included the modell column, and another table to show which manufacturers produce each art_nr. In this problem, you wouldn't need the manufacturers table, and the other table already has unique art_nrs, so you wouldn't need anything like the sub-query table_2_summary.
    Don't store price in a VARCHAR2 column. Storing NUMBERs in a VARCHAR2 column is just asking for problems. Why not use a NUMBER column instead.
    You'll notice that I used ROUND (SUM ... where you use SUM ( ROUND. The results might be a little different because of rounding errors. ROUND ( SUM only has to call ROUND once per group (5 times in this example) instead of once per row (16 times in this example). The less rounding you do, the less rounding error creeps in. Also, since there are fewer function calls, it's more convenient. (Of course, you'll never notice the difference between calling ROUND 5 times or 16 times, but in a real-life exampe, the difference could be between calling it 50 times or calling it 16000 times.) If you really need to use SUM (ROUND, you can.

  • Learning SQL Query with JCheckBox and JButton

    Hello,
    I am learning how to access a very simple Access table. I am able to connect to the database and return a simple query. As I make it more complicated is where I have confused myself. The program is suppose to allow the user to pick any field they want to query using JCheckBox. After they have checked the fields off, the run query button is hit and outputs the results in a JOPtion Pane with a JTable. I am trying to do a test run and I can't make the query at least output something. If I can get any clues to the right direction would be appreciated. Thanks.
    package mypackage25;
    import java.sql.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class QueryAddressBook extends JFrame
        private JLabel selectQueryLabel;
        private JCheckBox firstName, lastName,
                       telephone, addressI, addressII, city,
                       state, zip;
        private JPanel selectQueryPanel, checkBoxPanel, executePanel;
        private JButton runQueryButton, clearSQLButton;
        private Connection connection;
        private Statement statement;
        private ResultSet resultSet;
        public QueryAddressBook()
          super("Query an Address Book");
          //Driver and Connection
          try
          //Driver for MicrosoftAccess
          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
          //Inform the user that the Driver was loaded successfully
          System.out.println("Driver Loaded");
          //Connect to specific database(i.e. MyAddress3) in Access
          Connection connection=DriverManager.getConnection("jdbc:odbc:MyAddress3");
          //Inform User
          System.out.println("Database connected");
          }//end try
          catch(ClassNotFoundException cnfe)
            cnfe.printStackTrace();
          }//end catch
          catch(SQLException sqle)
            sqle.printStackTrace();
          }//end catch
          //get content pane and set its layout
          Container container=getContentPane();
          container.setLayout(new BorderLayout());
          //GUI Components
          selectQueryLabel=new JLabel("Select Fields to be Queried");
          firstName=new JCheckBox("First Name");
          lastName=new JCheckBox("Last Name");
          telephone=new JCheckBox("Telephone");
          addressI=new JCheckBox("Address I");
          addressII=new JCheckBox("Address II");
          city=new JCheckBox("City");
          state=new JCheckBox("State");
          zip=new JCheckBox("Zipcode");
          //register listeners for JCheckBoxes
          CheckBoxHandler handler=new CheckBoxHandler();
          firstName.addItemListener(handler);
          lastName.addItemListener(handler);
          telephone.addItemListener(handler);
          addressI.addItemListener(handler);
          addressII.addItemListener(handler);
          city.addItemListener(handler);
          state.addItemListener(handler);
          zip.addItemListener(handler);
          //set up selectQueryPanel
          selectQueryPanel=new JPanel();
          selectQueryPanel.setLayout(new FlowLayout());
          selectQueryPanel.add(selectQueryLabel);
          //set up CheckBox Panel
          checkBoxPanel=new JPanel();
          checkBoxPanel.setLayout(new FlowLayout());
          checkBoxPanel.add(firstName);
          checkBoxPanel.add(lastName);
          checkBoxPanel.add(telephone);
          checkBoxPanel.add(addressI);
          checkBoxPanel.add(addressII);
          checkBoxPanel.add(city);
          checkBoxPanel.add(state);
          checkBoxPanel.add(zip);
          //set up execute panel
          executePanel=new JPanel();
          executePanel.setLayout(new FlowLayout());
          //set up buttons
          runQueryButton=new JButton("Run Query");
          clearSQLButton=new JButton("Clear SQL");
          runQueryButton.addActionListener
            new ActionListener()
              public void actionPerformed(ActionEvent event)
                if(event.getSource().equals(runQueryButton))
                  runSQLQuery();
          executePanel.add(runQueryButton);
          executePanel.add(clearSQLButton);
          container.add(selectQueryPanel, BorderLayout.NORTH);
          container.add(checkBoxPanel, BorderLayout.CENTER);
          container.add(executePanel, BorderLayout.SOUTH);
          setSize(800,150);
          setVisible(true);
        public static void main(String args[])
          QueryAddressBook dwgui=new QueryAddressBook();
          dwgui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }//end main
        //private inner class for ItemListener event handling
        private class CheckBoxHandler implements ItemListener
          public void itemStateChanged(ItemEvent event)
          }//end method itemStateChanged
        }//end private inner class CheckBoxHandler
        private void runSQLQuery()
          String output="";
          try
            statement=connection.createStatement();
            resultSet=statement.executeQuery("select firstName from address");
            while(resultSet.next())
              output+=resultSet.getString(1)+"\n";
            JOptionPane.showMessageDialog(null,output);
            System.out.println(output);
          }//end try
          catch(SQLException sqle)
            sqle.printStackTrace();
          }//end catch
        }//end runSQLQuery
    }//end class

    At present your query string is
    "Select firstName from Address"
    Instead of using the above hardcoded string, try to build the
    query String using logic that checks which check boxes are selected
    by the user.
    Example..
    String query = "SELECT ";
    if (firstName.isSelected()) {
    query = query + " firstName";
    Be sure, you add the comma properly between two fields :-)

  • Request help to display a list with parent and child list item.

    I created a static list with items A,B,C and a child item A1 under parent A. I chose the template "vertical Side bar list". I am using theme 10 (sand) for my application. I created page 0 and am displaying the list on page template region position2. I am able to see the side bar with options A,B,C. But am not able to see the child option A1 when I click on Option A. I tried using 'DHTML MENU WITH SUB LIST' but When I click on option A, the child entry A1 is showing over the B and C options. I know this might be a pretty basic functionality. I am new to APEX and am just learning. I appreciate any help you give me.

    Mr.Backstrom,
    I have changed the list template overide to dhtml Tree. And now the list is being displayed as vertical unordered list with bullets. Is it possible to take off the bullets? Thank you for your time.
    Suma.

  • Oracle sql query with data aggregation

    Hi,
    I need help to aggregate sql result as given below
    Result what I get :
    Project Id | Project Name | Employee ID | Task Count
    1 :::::::::::| Project01 ::::::| 254 :::::::::::::| 20
    1 :::::::::::| Project01 ::::::| 266 :::::::::::::| 32
    1 :::::::::::| Project01 ::::::| 654 :::::::::::::| 12
    2 :::::::::::| Project02 ::::::| 741 :::::::::::::| 54
    2 :::::::::::| Project02 ::::::| 266 :::::::::::::| 31
    3 :::::::::::| Project03 ::::::| 877 :::::::::::::| 8
    3 :::::::::::| Project03 ::::::| 955 :::::::::::::| 19
    Result should come like this :
    Project Id | Project Name | Employee ID | Task Count
    1 :::::::::::| Project01 ::::::| 254 :::::::::::::| 20
    ::::::::::::::| ::::::::::::::::::::| 266 :::::::::::::| 32
    ::::::::::::::| ::::::::::::::::::::| 654 :::::::::::::| 12
    2 :::::::::::| Project02 ::::::| 741 :::::::::::::| 54
    ::::::::::::::| ::::::::::::::::::::| 266 :::::::::::::| 31
    3 :::::::::::| Project03 ::::::| 877 :::::::::::::| 8
    ::::::::::::::| ::::::::::::::::::::| 955 :::::::::::::| 19
    I need to know whether this is possible using only sql and how to do ? (Please ignore the colons)
    Thanks

    please learn how to use tags
    [code]
    Project Id | Project Name | Employee ID | Task Count
    1          | Project01    | 254         | 20
               |              | 266         | 32
               |              | 654         | 12
    2          | Project02    | 741         | 54
               |              | 266         | 31
    3          | Project03    | 877         | 8 
               |              | 955         | 19
    [/code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Need query to link parent and child discrete job planned through ascp

    Could you help me create a query that will show both the parent and child discrete jobs created through ascp run? I do not need entire query. I need to know the names of tables and understand the links or joins between tables. Then, I shall be able to write the sql on my own.
    Thanks

    Hi;
    Please check below thread which could be helpful for your issue:
    http://forums.oracle.com/forums/thread.jspa?messageID=9155702
    Regard
    Helios

  • Hierarchy query showing  parent and their child records

    I'm a newbie on Oracle using Tora,
    I'm Trying to run a query that will show me a hierarchical view of parent and child records in a table.
    So far I"ve found a query format like this, but its not working
    SELECT employee_id, last_name, manager_id
    FROM employees
    CONNECT BY PRIOR employee_id = manager_id;
    but when running it with my tables and columns I get an error message
    saying something 'cannont run CONNECT BY in subquery'
    Any ideas?

    Thanks for all the help, I'm getting the error message
    'ORA-01473: cannot have subqueries in CONNECT BY clause'
    Here's my actual query
    select           resource_id, lname, org_id
    from           std_resource
    start with      resource_id = 413783
         connect by prior resource_id = org_id;
    I'm trying to display a hierarchical list of user resource_id's, last names, and org_id's from the std_resource table starting withe resource_id 413783

Maybe you are looking for

  • Wrap text options, are they really limited?

    I was curious if there was a way to dial in precise NONuniform wrapping options. I have a place holder box that I want the text to wrap around and give a 5pt space on all but the right side... I want that 20pts. In the wrap text options it's all unif

  • JDBC transactions in EJB 3.0

    We have an EJB 3.0 method that call some jdbc DAO methods. This DAO methods called from controller (servlet) works fine, but when called from EJB method raise the following exception: "java.sql.SQLException: Cannot call Connection.commit in distribut

  • BBP_WFL_APPROV_BADI - There are already implementations active

    Hi I was thinking about using badi BBP_WFL_APPROV_BADI to set up different approvers for approval of the Shopping Cart in SRM. But unfortunately I get the message "There are already implementations active". Looks like SAP is already using this BADI.

  • Subtitle generator for dvd sp 4

    Hi I need to create subtitles for a dvd I am makeing with version 4. I used to do it in subtitle editor 1 for dvd sp 1.5, but this does not work anymore acording to the manual, but it does not say how to do it. Thanks in advance for any help Pepo

  • Monitor HTTP Sessions

    Hi, I want to monitor all http sessions on the SAP Portal. For this I know two possibilities - In the Visual Administrator -> Security Provider you can access the login sessions, but these are only the sessions of the authenticated users - In the Net