SQL Query -- Please Help

Table1
QTE_ID     SEQ_NO
1435177     2
1435177     5
1435177     7
1435177     8
1435177     12
1435177     14
Table2
QTE_ID     SEQ_NO     CMMT_CURR_AMT
1435177     1     98500
1435177     2     98500
1435177     3     0
1435177     4     98500
1435177     5     98500
1435177     7     98500
1435177     8     98500
1435177     11     59300
1435177     12     59300
1435177     14     59300
The result should be
QTE_ID     SEQ_NO     CMMT_CURR_AMT
1435177     2     0 (where 0 = cmmt_curr_amt of seq 2 - cmmt_curr_amt of seq 1 from table 2)
1435177     5     0 (where 0 = cmmt_curr_amt of seq 5 - cmmt_curr_amt of seq 4 from table 2)
1435177     7     0 (where 0 = cmmt_curr_amt of seq 7 - cmmt_curr_amt of seq 5 from table 2)
1435177     8     0 (where 0 = cmmt_curr_amt of seq 8 - cmmt_curr_amt of seq 7 from table 2)
1435177     12     0 (where 0 = cmmt_curr_amt of seq 12 - cmmt_curr_amt of seq 11 from table 2)
1435177     14     0 (where 0 = cmmt_curr_amt of seq 14 - cmmt_curr_amt of seq 12 from table 2)
I have to get the difference of cmmt_curr_amt from the table2 from seq 14 to seq 12 for seq14 in table 1.
Please help me in writing the query.
Thanks in advance.
Srinivas

WITH table1 AS
(SELECT 1435177 qte_id, 2 seq_no
FROM dual
UNION ALL
SELECT 1435177 qte_id, 5 seq_no
FROM dual
UNION ALL
SELECT 1435177 qte_id, 7 seq_no
FROM dual
UNION ALL
SELECT 1435177 qte_id, 8 seq_no
FROM dual
UNION ALL
SELECT 1435177 qte_id, 12 seq_no
FROM dual
UNION ALL
SELECT 1435177 qte_id, 14 seq_no
FROM dual
table2 AS
SELECT 1435177 qte_id, 1 seq_no, 98500 cmmt_curr_amt
FROM dual
UNION ALL
SELECT 1435177 qte_id, 2 seq_no, 98500 cmmt_curr_amt
FROM dual
UNION ALL
SELECT 1435177 qte_id, 3 seq_no, 0 cmmt_curr_amt
FROM dual
UNION ALL
SELECT 1435177 qte_id, 4 seq_no, 98500 cmmt_curr_amt
FROM dual
UNION ALL
SELECT 1435177 qte_id, 5 seq_no, 98500 cmmt_curr_amt
FROM dual
UNION ALL
SELECT 1435177 qte_id, 7 seq_no, 98500 cmmt_curr_amt
FROM dual
UNION ALL
SELECT 1435177 qte_id, 8 seq_no, 98500 cmmt_curr_amt
FROM dual
UNION ALL
SELECT 1435177 qte_id, 11 seq_no, 59300 cmmt_curr_amt
FROM dual
UNION ALL
SELECT 1435177 qte_id, 12 seq_no, 59300 cmmt_curr_amt
FROM dual
UNION ALL
SELECT 1435177 qte_id, 14 seq_no, 59300 cmmt_curr_amt
FROM dual
SELECT qte_id, t2_seq_no, cmmt_curr_amt - cmmt_curr_lag diff
FROM
(SELECT t2.qte_id, t2.seq_no t2_seq_no, t1.seq_no t1_seq_no, cmmt_curr_amt, LAG(cmmt_curr_amt,1,0) OVER (PARTITION BY t2.qte_id ORDER BY t2.seq_no) cmmt_curr_lag
FROM table1 t1, table2 t2
WHERE t2.qte_id = t1.qte_id (+)
AND t2.seq_no = t1.seq_no(+)
ORDER BY 1,2
WHERE t1_seq_no IS NOT NULL
ORDER BY 1,2
QTE_ID T2_SEQ_NO DIFF
1435177 2 0
1435177 5 0
1435177 7 0
1435177 8 0
1435177 12 0
1435177 14 0

Similar Messages

  • Cluster bar chart- sql query please help-

    Hi,
    I am trying to create cluster bar chart and am stumped with this sql query.Any help is appreciated.
    Here is my table
    city     region      issue     value
    c1     north     i1     y
    c1     north     i2     y
    c2     north     i1     n
    c2     north     i2     y
    c3     south     i1     y
    c3     south     i2     n
    c4     east     i1     n
    c4     east     i2     n
    The bar chart will have 3 series, north south and east.
    And labels will be i1 and i2. value will be number of times this issue was encountered(y) in this region.
    How can I get something like this from the above table-
    region     issue     count(yes)
    north     i1     1
    north     i2     2
    south     i1     1
    south     i2     0
    east     i1     0
    east     i2     0
    thanks

    WITH table1 AS
    (SELECT 1435177 qte_id, 2 seq_no
    FROM dual
    UNION ALL
    SELECT 1435177 qte_id, 5 seq_no
    FROM dual
    UNION ALL
    SELECT 1435177 qte_id, 7 seq_no
    FROM dual
    UNION ALL
    SELECT 1435177 qte_id, 8 seq_no
    FROM dual
    UNION ALL
    SELECT 1435177 qte_id, 12 seq_no
    FROM dual
    UNION ALL
    SELECT 1435177 qte_id, 14 seq_no
    FROM dual
    table2 AS
    SELECT 1435177 qte_id, 1 seq_no, 98500 cmmt_curr_amt
    FROM dual
    UNION ALL
    SELECT 1435177 qte_id, 2 seq_no, 98500 cmmt_curr_amt
    FROM dual
    UNION ALL
    SELECT 1435177 qte_id, 3 seq_no, 0 cmmt_curr_amt
    FROM dual
    UNION ALL
    SELECT 1435177 qte_id, 4 seq_no, 98500 cmmt_curr_amt
    FROM dual
    UNION ALL
    SELECT 1435177 qte_id, 5 seq_no, 98500 cmmt_curr_amt
    FROM dual
    UNION ALL
    SELECT 1435177 qte_id, 7 seq_no, 98500 cmmt_curr_amt
    FROM dual
    UNION ALL
    SELECT 1435177 qte_id, 8 seq_no, 98500 cmmt_curr_amt
    FROM dual
    UNION ALL
    SELECT 1435177 qte_id, 11 seq_no, 59300 cmmt_curr_amt
    FROM dual
    UNION ALL
    SELECT 1435177 qte_id, 12 seq_no, 59300 cmmt_curr_amt
    FROM dual
    UNION ALL
    SELECT 1435177 qte_id, 14 seq_no, 59300 cmmt_curr_amt
    FROM dual
    SELECT qte_id, t2_seq_no, cmmt_curr_amt - cmmt_curr_lag diff
    FROM
    (SELECT t2.qte_id, t2.seq_no t2_seq_no, t1.seq_no t1_seq_no, cmmt_curr_amt, LAG(cmmt_curr_amt,1,0) OVER (PARTITION BY t2.qte_id ORDER BY t2.seq_no) cmmt_curr_lag
    FROM table1 t1, table2 t2
    WHERE t2.qte_id = t1.qte_id (+)
    AND t2.seq_no = t1.seq_no(+)
    ORDER BY 1,2
    WHERE t1_seq_no IS NOT NULL
    ORDER BY 1,2
    QTE_ID T2_SEQ_NO DIFF
    1435177 2 0
    1435177 5 0
    1435177 7 0
    1435177 8 0
    1435177 12 0
    1435177 14 0

  • Passing parameter to a SQL query - Please help

    Hi All,
    I am new to JDBC. I have been trying to pass an external variable to an SQL Query.
    The query is
    String username1="le";
    PreparedStatement pstmt = null;
    pstmt = c.prepareStatement("select * from users where USER_NAME like '%?%'");
         pstmt.setString(1, username1);
         pstmt.executeQuery();
         ResultSet rs = pstmt.getResultSet();
    I am trying to retrieve values from the users table where the USER_NAME column value that is a String contains the supplied value username1.
    I am using the question mark (?) character to pass the value from the variable username1. I am also using the '%' substitution character which matches for any number of characters. So, the above query should retrieve rows where the USER_NAME is something like "charles","leander","Elena" etc.( that contains "le")
    I am getting the error:
    SQLException: java.sql.SQLException: ORA-01006: bind variable does not exist
    I changed the query to
    PreparedStatement pstmt = null;
    pstmt = c.prepareStatement("select * from users where USER_NAME like '% " + username1 + "%'");
         //pstmt.setString(1, username1);
         pstmt.executeQuery();
    This time , it is not giving the error and retrieving properly.
    But I want to use the original query and use the "pstmt.setString(1, username1); " . Is there any way of achieving this?
    Please help.
    Cheers,
    charles_am

    hi,
    try this...
    String username1="%le%";
    pstmt = c.prepareStatement("select * from users where USER_NAME like ?")
    pstmt.setString(1,username1);
    cheers,
    rpk

  • Single sql query-please help

    Hi experts,
    what i want to do is write a single query which will show whether a employee
    exits in the company or not.I have two tables emp and dept.There are as follows.
    SQL> select * from emp;
    NAME DEPTNO EMPNO
    xxx 10 33036
    YYY 12 2345
    ZZZ 13 678
    KKK 14 5678
    RRR 15 7865
    SQL> select * from dept;
    DEPTNO LOCATION
    10 AAA
    11 BBB
    12 CCC
    13 DDD
    what i want is it will select records from the emp table and find whether corrosponding
    deptno really exists in the dept table.If the value is found in deptno column the dept table then it will set the value
    Y other wise it will be N and all i have to do with the help of a single query.
    expected result
    name empno exists
    xxx 33036 Y
    YYY 2345 Y
    ZZZ 678 Y
    KKK 5678 N
    RRR 7865 N
    Please help.
    Regards
    Rajat

    SELECT EMPNO, NAME , EMPNO , NVL( ( SELECT 'Y' FROM    DEPT WHERE EMP.DEPTNO=DEPT.DEPTNO),'N') EXIST
    FROM EMP
    ORDER BY 1
    Demo
    SQL> WITH EMP AS(
      2  SELECT 'XXX' NAME , 10 DEPTNO ,33036  EMPNO FROM DUAL UNION
      3  SELECT 'YYY', 12, 2345 FROM DUAL UNION
      4  SELECT 'ZZZ', 13 ,678 FROM DUAL UNION
      5  SELECT 'KKK', 14 ,5678 FROM DUAL UNION
      6  SELECT 'RRR', 15 ,7865 FROM DUAL  ),
      7  DEPT AS(
      8  SELECT 10  DEPTNO,'AAA' DNAME FROM DUAL UNION
      9  SELECT 11 ,'BBB' FROM DUAL UNION
    10  SELECT 12 ,'CCC' FROM DUAL UNION
    11  SELECT 13 ,'DDD'FROM DUAL )
    12  SELECT EMPNO, NAME , EMPNO , NVL( ( SELECT 'Y' FROM    DEPT WHERE EMP.DEPTNO=DEPT.DEPTNO),'N')
    EXIST
    13  FROM EMP
    14  ORDER BY 1
    15  /
         EMPNO NAM      EMPNO E
           678 ZZZ        678 Y
          2345 YYY       2345 Y
          5678 KKK       5678 N
          7865 RRR       7865 N
         33036 XXX      33036 Y
    SQL> Edited by: Salim Chelabi on Dec 7, 2008 4:15 AM

  • I need to denormalize data in sql query, please help!

    With the query
    select ref, start_time, end_time, person
    from appointments
    I get, eg:
    REF START_TIME END_TIME PERSON
    1234 10:00 11:00 USER1
    1234 10:00 11:00 USER2
    The users want to see it like this:
    REF START_TIME END_TIME PERSON
    1234 10:00 11:00 USER1, USER2
    How do I do this just in sql?
    cheers
    Tracey.

    Apologies, my mistake, I forgot to connect by the ref as well...
    (Note: you can ignore the CAST to VARCHAR2(40) as that just helped me get the formatted output.)
    SQL> ed
    Wrote file afiedt.buf
      1  with t as (select 1234 as ref, '10:00' as start_time, '11:00' as end_time, 'USER1' as person from dual union all
      2             select 1234, '10:00', '11:00', 'USER2' from dual union all
      3             select 345, '11:00', '12:00', 'USER3' from dual)
      4  -- END OF TEST DATA
      5  select ref, start_time, end_time, CAST(MAX(LTRIM(SYS_CONNECT_BY_PATH(person,', '),', ')) AS VARCHAR2(40)) as users
      6  from (select ref, start_time, end_time, person
      7              ,row_number() over (partition by ref, start_time, end_time order by person) rn
      8        from t) t
      9  CONNECT BY rn = PRIOR rn+1 AND ref = PRIOR ref
    10  START WITH rn = 1
    11* GROUP BY ref, start_time, end_time
    SQL> /
           REF START END_T USERS
          1234 10:00 11:00 USER1, USER2
           345 11:00 12:00 USER3
    SQL>

  • SQL Query, please help very urgent

    I am a newbie is sql.
    I have two tables called test_master and test_detail.
    Both tables contains pos_id as common field.
    In test_detail got sub_id and to get the people under a given pos_id, I join with pos_id of test_master.
    In the where condition, when I give the pos_id, it's returning only
    the first level. How can I get the second level and get all the levels?
    Any help is highly appreciable.It's very urgent.
    Looking forward to hear from you.
    Thanks
    Newbie

    Ok, I am pasting the description of the master and detail in the order.
    Master
    EMPLOYEE_NO VARCHAR2(30)
    ORGANIZATION_ID NUMBER(15)
    ORGANIZATION_NAME VARCHAR2(240)
    POSITION_ID NUMBER(15)
    POSITION_NAME VARCHAR2(240)
    Detail
    POSITION_ID NUMBER(15)
    SUBORDINATE_ID NUMBER(15)
    ORGANIZATION_ID NUMBER(15)
    POSITION_NAME VARCHAR2(50)
    Here is the sql, I want to get all the subordinates under a given position_id of the master.
    Looking forward to hear from you.
    select a.employee_no,a.POSITION_ID,a.POSITION_NAME,a.EMPLOYEE_NAME,
    b.position_id,b.subordinate_id from portal_employee_master_test a,
    portal_structure_test b
    where a.POSITION_ID = b.POSITION_ID and a.POSITION_ID='xyz'
    and b.position_ID=a.POSITION_ID

  • I need sql query please help me out

    I have two databases 1) erp 2) edusource
    In erp database i  have table  master tables and  columns  like RecordId , value type ,Feildtext,description,Meaining,parentid etc
     data stores based on value type like
    1
    Country
    In
    India
    NULL
        NULL
    True
    2
    Country
    Aus
    Austrilia
    NULL
        NULL
    True
    3
    Country
    Usa
    United States of America
    NULL
        NULL
    True
    4
    Country
    Uk
    Great Britian
    NULL
        NULL
    True
    5
    State
    AP
    Andhrapradesh
    NULL
         1
    True
    6
    State
    MH
    Maharastha
    NULL
         1
    True
    7
    State
    TN
    Tamilnadu
    NULL
         1
    True
    8
    State
    Sdy
    Sydney
    NULL
         2
    True
    9
    State
    MEL
    Melbourne
    NULL
    2
    True
    10
    Location
    IN-Hyd
    Hyderabad
    NULL
    1
    True
    11
    Location
    In SEz
    Sez-Hyderabad
    NULL
    1
    True
    NULL
    NULL
    NULL
    NULL
    NULL
    NULL
    NULL
    for  country and state we have a relation ship parentid and recordid
    country
    1 Country
    In India
                                       NULL
    NULL 1
    2 Country
    Aus Austrilia
                               NULL
    NULL 1
    3 Country
    Usa United States of America    NULL
    NULL 1
    4 Country
    Uk Great Britian
                    NULL
    NUL          1 
    5 State
    AndhraPradesh Ap
    NULL 1
    1
    6 State
    Maharastha MH
    NULL 1
    1
    7 State
    Tamilnadu        TN
    NULL        1
    1
    8 State
    Sydney            Sdy   NULL
          2 1
    9 State        Melbourne       MEL
    NULL       2
    1
      in edusource  database i have location and columns like countryname,statename,feildtext,descriptiom,isactive
    i need to insert data in edusource
     database of tbl_ maplocation from that that database

    Try this out:
    DECLARE @geog TABLE (ID INT, type VARCHAR(20), Abrev VARCHAR(6), name VARCHAR(30), parentID INT, Active VARCHAR(5))
    INSERT INTO @geog (ID, type, Abrev, name, parentID, Active) VALUES
    (1 , 'Country' ,'In ', 'India ', NULL, 'TRUE'),(2 , 'Country' ,'Aus ', 'Austrilia ', NULL, 'TRUE'),
    (3 , 'Country' ,'Usa ', 'United States of America', NULL, 'TRUE'),(4 , 'Country' ,'Uk ', 'Great Britian ', NULL, 'TRUE'),
    (5 , 'State' ,'AP ', 'Andhrapradesh ', 1 , 'TRUE'),(6 , 'State' ,'MH ', 'Maharastha ', 1 , 'TRUE'),
    (7 , 'State' ,'TN ', 'Tamilnadu ', 1 , 'TRUE'),(8 , 'State' ,'Sdy ', 'Sydney ', 2 , 'TRUE'),
    (9 , 'State' ,'MEL ', 'Melbourne ', 2 , 'TRUE'),(10 , 'Location' ,'IN-Hyd', 'Hyderabad ', 1 , 'TRUE'),
    (11 , 'Location' ,'In SEz', 'Sez-Hyderabad ', 1 , 'TRUE')
    SELECT g1.ID, COALESCE(g2.name,g1.name) AS countryName, g1.name AS stateName, g1.name AS fieldText, CASE WHEN COALESCE(g2.Active,'TRUE') = 'TRUE' AND g1.Active = 'TRUE' THEN 'TRUE' ELSE 'FALSE' END AS Active
    FROM @geog g1
    LEFT OUTER JOIN @geog g2
    ON g1.parentID = g2.ID
    AND g1.type IN ('location','state')
    WHERE g1.Active = 'TRUE'
    AND COALESCE(g2.Active,'TRUE') = 'TRUE'
    I think you may want to further the relationship, and have 10 be the parent for 11, so you can get country, state, location.

  • SQL experts please help for a query

    I have following table1.
    What query can give the result as given below, SQL experts please help on this.
    TABLE1
    Event DATETIME
    in 2/JAN/2010
    out 2/JAN/2010
    in 13/JAN/2010
    out 13/JAN/2010
    in 5/JAN/2010
    out 5/JAN/2010
    RESULT REQUIRED FROM THE SQL QUERY
    COL1_IN COL2_OUT
    2/JAN/2010 2/JAN/2010
    13/JAN/2010 13/JAN/2010
    5/JAN/2010 5/JAN/2010

    I tried to help, but this puzzles me.
    Why is this not returning pre-selected set of rows, why it's doing some merge join cartezian ?
    SQL> select * from v$version;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - Prod
    PL/SQL Release 10.2.0.4.0 - Production
    CORE    10.2.0.4.0      Production
    TNS for Linux: Version 10.2.0.4.0 - Production
    NLSRTL Version 10.2.0.4.0 - Production
    SQL> select * from table1;
    EVENT      DATETIME
    in         2/JAN/2010
    out        2/JAN/2010
    in         13/JAN/2010
    out        13/JAN/2010
    in         5/JAN/2010
    out        5/JAN/2010
    6 rows selected.
    SQL> explain plan for
      2  with a as
    (select datetime from table1 where event='in'),
    b as
    (select datetime from table1 where event='out')
    select  a.datetime COL1_IN ,b.datetime COL2_OUT from a,b ;
    Explained.
    SQL> set wrap off
    SQL> set linesize 200
    SQL> select * from table(dbms_xplan.display);
    PLAN_TABLE_OUTPUT
    Plan hash value: 185132177
    | Id  | Operation            | Name   | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT     |        |     9 |   288 |     8   (0)| 00:00:01 |
    |   1 |  MERGE JOIN CARTESIAN|        |     9 |   288 |     8   (0)| 00:00:01 |
    |*  2 |   TABLE ACCESS FULL  | TABLE1 |     3 |    48 |     3   (0)| 00:00:01 |
    |   3 |   BUFFER SORT        |        |     3 |    48 |     5   (0)| 00:00:01 |
    |*  4 |    TABLE ACCESS FULL | TABLE1 |     3 |    48 |     2   (0)| 00:00:01 |
    PLAN_TABLE_OUTPUT
    Predicate Information (identified by operation id):
       2 - filter("EVENT"='in')
       4 - filter("EVENT"='out')
    Note
       - dynamic sampling used for this statement
    21 rows selected.
    SQL> with a as
    (select datetime from table1 where event='in'),
    b as
    (select datetime from table1 where event='out')
    select  a.datetime COL1_IN ,b.datetime COL2_OUT from a,b ;
    COL1_IN         COL2_OUT
    2/JAN/2010      2/JAN/2010
    2/JAN/2010      13/JAN/2010
    2/JAN/2010      5/JAN/2010
    13/JAN/2010     2/JAN/2010
    13/JAN/2010     13/JAN/2010
    13/JAN/2010     5/JAN/2010
    5/JAN/2010      2/JAN/2010
    5/JAN/2010      13/JAN/2010
    5/JAN/2010      5/JAN/2010
    9 rows selected.
    SQL>

  • How to improve the performance of the attached query, Please help

    Hi,
    How to improve performance of the below query, Please help. also attached explain plan -
    SELECT Camp.Id,
    rCam.AccountKey,
    Camp.Id,
    CamBilling.Cpm,
    CamBilling.Cpc,
    CamBilling.FlatRate,
    Camp.CampaignKey,
    Camp.AccountKey,
    CamBilling.billoncontractedamount,
    (SUM(rCam.Impressions) * 0.001 + SUM(rCam.Clickthrus)) AS GR,
    rCam.AccountKey as AccountKey
    FROM Campaign Camp, rCamSit rCam, CamBilling, Site xSite
    WHERE Camp.AccountKey = rCam.AccountKey
    AND Camp.AvCampaignKey = rCam.AvCampaignKey
    AND Camp.AccountKey = CamBilling.AccountKey
    AND Camp.CampaignKey = CamBilling.CampaignKey
    AND rCam.AccountKey = xSite.AccountKey
    AND rCam.AvSiteKey = xSite.AvSiteKey
    AND rCam.RmWhen BETWEEN to_date('01-01-2009', 'DD-MM-YYYY') and
    to_date('01-01-2011', 'DD-MM-YYYY')
    GROUP By rCam.AccountKey,
    Camp.Id,
    CamBilling.Cpm,
    CamBilling.Cpc,
    CamBilling.FlatRate,
    Camp.CampaignKey,
    Camp.AccountKey,
    CamBilling.billoncontractedamount
    Explain Plan :-
    Description                    Object_owner          Object_name     Cost     Cardinality     Bytes     
    SELECT STATEMENT, GOAL = ALL_ROWS                              14     1     13
    SORT AGGREGATE                                                  1     13
    VIEW                         GEMINI_REPORTING               14     1     13
    HASH GROUP BY                                        14     1     103
    NESTED LOOPS                                        13     1     103
    HASH JOIN                                             12     1     85
    TABLE ACCESS BY INDEX ROWID     GEMINI_REPORTING     RCAMSIT          2     4     100
    NESTED LOOPS                                        9     5     325
    HASH JOIN                                        7     1     40
    SORT UNIQUE                                        2     1     18
    TABLE ACCESS BY INDEX ROWID     GEMINI_PRIMARY          SITE          2     1     18
    INDEX RANGE SCAN          GEMINI_PRIMARY          SITE_I0          1     1     
    TABLE ACCESS FULL          GEMINI_PRIMARY          SITE          3     27     594
    INDEX RANGE SCAN          GEMINI_REPORTING     RCAMSIT_I     1     1     5     
    TABLE ACCESS FULL     GEMINI_PRIMARY     CAMPAIGN                    3     127     2540
    TABLE ACCESS BY INDEX ROWID     GEMINI_PRIMARY          CAMBILLING     1     1     18
    INDEX UNIQUE SCAN     GEMINI_PRIMARY     CAMBILLING_U1                    0     1

    Hello,
    This has really nothing to do with the Oracle Forms product.
    Please, send the SQL or/and PL/SQL questions in the corresponding forums.
    Francois

  • How to make recursive query.Please help

    Dear Experts:
    I want to retrieve all employees located in a department in addition to all other employees located in the child's nodes of this department too.
    Problem Details:
    I have "Employees" table and "Departments" Table
    The structure of Dept Table is:
    ID   primary key
    parent_dept   foreign key(id)
    deptname  varchar2
    deptType varchar2
    The Employee table structure is
    ID primary key
    dept_id foreign key(Department.id)
    empName varchar2Sample data for departments
    ID : 1
    parent_dept : null
    deptname: General Manager office
    deptType : 'GM'
    ID :=2
    parent_dept : 1
    deptname: Information tech.
    deptType : 'DPT'
    ID :=3
    parent_dept : 2
    deptname: Software Development
    deptType : 'SECTION'Sample Data for employees
    ID : 101
    dept_id  :1
    empName  King
    ID : 102
    dept_id  :2
    empName  ALAN
    ID : 103
    dept_id  :2
    empName  SAM
    ID : 104
    dept_id  :3
    empName  JANEI want to create a query that accepts a parameter "p_department_id" and returns All employees on the following conditions
    1- In case the parameter value is null , then retrieve All Employees "king - alan- sam-jane"
    2- In Case the parameter value is 1 , then retrieve all the employees under department id =1 in addition to all the employees located under the children departments.
    in this case it will be "king - alan- sam-jane"
    3- In case parameter value is 2 , then return all the employees under department id =2 in addition to all the employees located under the children departments.
    In this case it will be " alan- sam-jane"
    4- In case parameter value is 3 , then return all the employees under department id =3 in addition to all the employees located under the children departments.
    in this case it will be only "JANE"
    In brief , If I pass any value to the parameter :p_department_id , I want to retrieve all employees located in this department in addition to other employees located in the child's nodes of this department id
    I use oracle database 11g release 2
    Please help me
    Thanks
    Edited by: ta**** on Apr 3, 2013 5:56 PM
    Edited by: ta**** on Apr 3, 2013 5:58 PM

    SQL> variable p_department_id number
    SQL> exec :p_department_id := null
    PL/SQL procedure successfully completed.
    SQL> with employees as (
      2                     select 101 id,1 dept_id,'King' empName from dual union all
      3                     select 102,2,'ALAN' from dual union all
      4                     select 103,2,'SAM' from dual union all
      5                     select 104,3,'JANE' from dual
      6                    ),
      7     departments as (
      8                     select 1 id,null parent_dept,'General Manager office' deptname,'GM' deptType from dual union all
      9                     select 2,1,'Information tech.','DPT' from dual union all
    10                     select 3,2,'Software Development','SECTION' from dual
    11                    )
    12  select  *
    13    from  employees
    14    where dept_id in (
    15                      select  id
    16                        from  departments
    17                        start with (
    18                                       (
    19                                            :p_department_id is null
    20                                        and
    21                                            parent_dept is null
    22                                       )
    23                                    or
    24                                       id = :p_department_id
    25                                   )
    26                        connect by parent_dept = prior id
    27                     )
    28  /
            ID    DEPT_ID EMPN
           101          1 King
           102          2 ALAN
           103          2 SAM
           104          3 JANE
    SQL> exec :p_department_id := 1
    PL/SQL procedure successfully completed.
    SQL> /
            ID    DEPT_ID EMPN
           101          1 King
           102          2 ALAN
           103          2 SAM
           104          3 JANE
    SQL> exec :p_department_id := 2
    PL/SQL procedure successfully completed.
    SQL> /
            ID    DEPT_ID EMPN
           102          2 ALAN
           103          2 SAM
           104          3 JANE
    SQL> exec :p_department_id := 3
    PL/SQL procedure successfully completed.
    SQL> /
            ID    DEPT_ID EMPN
           104          3 JANE
    SQL> SY.

  • SQL query tunning help

    Hi All,
    Could you please help me out the below SQL query tuning .
    Temp table is having 1 Million records
    Master table is having 60 Million records
    Query :
    SELECT B.*,U.ID, SD, LE, LAE
    FROM client.Temp B, client.Master
    U WHERE U.policyno = B.policyno
    AND B.UPFLAG = 0
    1.     Indexes are created on both email columns and Upflag for both tables.
    2.     Gathered DBMS Stats for MASTER Table
    Data is loading 100k/hour on production .

    When your query takes too long ...
    When your query takes too long ...
    HOW TO: Post a SQL statement tuning request - template posting
    HOW TO: Post a SQL statement tuning request - template posting

  • SQL question - please help!

    Hi,
    I am working on a SQL, please help ms with the question
    below .... thanks
    (1)Increase by 10% salary of these captain pilots who have
    traveled more than 800,000 miles.
    Routes | | Flights | |Pilots |
    | | | | |
    #routeID | | #flightNO | |#pilotID |
    depAirportID |        |  airplaneNO| |*name |
    arrAirportID |_______/|  pilotID |\___________|*hours_in_air|
    length       |       \|  routeID |/ |*grade |
    ______________| |_____________| |*salary |
    |____________|

    If the length column in routes is in hours, and it represents
    additional hours to those shown in hours_in_air in pilots, then
    the following should work:
    UPDATE pilots
    SET salary = salary * 1.1
    WHERE pilotid in (SELECT a.pilotid
    FROM pilots a,
         (SELECT b.pilotid,sum(c.length) new_hours
          FROM flights b, routes c
          WHERE b.routeid = c.routeid
          GROUP BY b.pilotid) d
    WHERE a.pilotid = d.pilotid and
          new_hours + hours_in_air >= 80000)I suspect that you probably need to add additional criteria to
    the sub-query from flights and routes to take into account only
    flights since the hours_in_air column from pilots was last
    updated. However, your table structures do not indicate any
    date sensitivity. If the table flights is emptied every time
    hours_in_air is updated, then the query above will work.

  • Sccm 2012 update complaince query ---please help

    hi
    i have 2 primary sites and 1 secondary my sites computers name start with NDY ,MYS,KES   need and sql query run against an update group  . i would like take total sum of each site computers and run against update group to find % complaince
    in each site .can any one help .after report is generated it should be in  below format
    total no computers in site (for each site separte count ) ,
     count of  computers  NDY ,MYS ,KES   -->  % of update complaince -->  ,% non  complaince update
    Please provide a sql query for this
    ankith

    I have below query from internet can any one help to modify this to create like the dashboard
    Select Deploymentname, Available, Deadline,           
    cast(((cast([Compliant] as float) / (ISNULL([Compliant], 0) + ISNULL([Enforcement state unknown], 0) + ISNULL([Successfully installed update(s)], 0) + ISNULL([Failed to install update(s)], 0) + ISNULL([Installing update(s)], 0) + ISNULL([Waiting for another
    installation to complete], 0) + ISNULL([Pending system restart], 0) + ISNULL([Downloading update(s)], 0)))*100) as Numeric(10,2)) AS ‘% Compliant’,            
      [Compliant],            
      [Enforcement state unknown],            
      [Successfully installed update(s)],            
      [Failed to install update(s)],            
      [Installing update(s)],            
      [Waiting for another installation to complete],            
      [Pending system restart],            
      [Downloading update(s)]            
    From            
    (select            
    a.AssignmentName as DeploymentName,            
    a.StartTime as Available,            
    a.EnforcementDeadline as Deadline,            
    sn.StateName as LastEnforcementState,            
    count(*) as NumberOfComputers            
    from v_CIAssignment a            
    join v_AssignmentState_Combined assc            
    on a.AssignmentID=assc.AssignmentID            
    join v_StateNames sn            
    on assc.StateType = sn.TopicType and sn.StateID=isnull(assc.StateID,0)            
    where AssignmentName NOT like ‘%_PREPROD_%’               
    group by a.AssignmentName, a.StartTime, a.EnforcementDeadline,            
          sn.StateName) as PivotData            
    PIVOT            
    SUM (NumberOfComputers)            
    FOR LastEnforcementState IN            
    ( [Compliant],            
      [Enforcement state unknown],            
      [Successfully installed update(s)],            
      [Failed to install update(s)],            
      [Installing update(s)],            
      [Waiting for another installation to complete],            
      [Pending system restart],            
      [Downloading update(s)])            
    ) AS pvt
    ankith

  • Query--please help

    Hello Forum Members,
    Can you please help me out:
    SQL> select * from quarter_test4;
    QUARTER CONFIG REP_DATE
    Q1-2007 10 12-JAN-07
    Q2-2007 10 21-APR-07
    Q3-2007 870 14-AUG-07
    Q4-2007 50 15-NOV-07
    Q1-2008 60 02-JAN-09
    Q4-2006 160 02-DEC-06
    I want the following out put:
    Please note that the future quarters should have current quarter sum(config).Please note that The current table
    does not hold future quarters.I have to genarate query on which a report is based.
    My Query:
    SELECT quarter,
    CASE
    WHEN qtr > TRUNC(SYSDATE, 'q')
    THEN LAST_VALUE(sum_config IGNORE NULLS) OVER(ORDER BY qtr)
    ELSE sum_config
    END sum_config
    FROM (SELECT qtr, q.qtrstr quarter, SUM(qt.config) sum_config
    FROM (SELECT 'Q' || TO_CHAR(qtr, 'q-yyyy') qtrstr, qtr
    FROM (SELECT ADD_MONTHS(ADD_MONTHS(TRUNC(SYSDATE, 'q'), -13), 3 *(LEVEL - 1)) qtr
    FROM DUAL
    CONNECT BY LEVEL <= 9)
    ORDER BY qtr) q,
    quarter_test4 qt
    WHERE qt.quarter(+) = q.qtrstr
    GROUP BY qtr, q.qtrstr)
    ORDER BY qtr;
    Correct Output Generated:
    QUARTER SUM_CONFIG
    Q4-2006 160
    Q1-2007 10
    Q2-2007 10
    Q3-2007 870
    Q4-2007 50
    Q1-2008 60
    Q2-2008 60
    Q3-2008 60
    Q4-2008 60
    ====================================================================================================================================
    New Requirement:Product column has been added.
    SQL> select * from quarter_test3;
    QUARTER CONFIG REP_DATE PRODUCT
    Q1-2007 10 12-JAN-07 P1
    Q2-2007 10 21-APR-07 P1
    Q3-2007 870 14-AUG-07 P1
    Q4-2007 50 15-NOV-07 P1
    Q1-2008 60 02-JAN-09 P1
    Q4-2006 160 02-DEC-06 P1
    Q4-2006 997 02-DEC-06 P2
    Q4-2007 60 14-NOV-07 P2
    Q3-2007 970 14-NOV-07 P2
    Q2-2007 20 21-APR-07 P2
    Q1-2007 20 12-JAN-07 P2
    QUARTER CONFIG REP_DATE PRODUCT
    Q1-2008 70 12-JAN-08 P2
    Expected Output:
    Q4-2006 160 P1
    Q1-2007 10 P1
    Q2-2007 10 P1
    Q3-2007 870 P1
    Q4-2007 50 P1
    Q1-2008 60 P1
    Q2-2008 60 P1
    Q3-2008 60 P1
    Q4-2008 60 P1
    Q4-2006 260 P2
    Q1-2007 20 P2
    Q2-2007 20 P2
    Q3-2007 970 P2
    Q4-2007 60 P2
    Q1-2008 70 P2
    Q2-2008 70 P2
    Q3-2008 70 P2
    Q4-2008 70 P2
    My Query:
    SELECT quarter,product,
    CASE
    WHEN qtr > TRUNC(SYSDATE, 'q')
    THEN LAST_VALUE(sum_config IGNORE NULLS) OVER(ORDER BY qtr)
    ELSE sum_config
    END sum_config
    FROM (SELECT qtr, q.qtrstr quarter,product, SUM(qt.config) sum_config
    FROM (SELECT 'Q' || TO_CHAR(qtr, 'q-yyyy') qtrstr, qtr
    FROM (SELECT ADD_MONTHS(ADD_MONTHS(TRUNC(SYSDATE, 'q'), -13), 3 *(LEVEL - 1)) qtr
    FROM DUAL
    CONNECT BY LEVEL <= 9)
    ORDER BY qtr) q,
    quarter_test3 qt
    WHERE qt.quarter(+) = q.qtrstr
    GROUP BY qtr,product, q.qtrstr)
    ORDER BY substr(qtr,-4),substr(QTR,2,1)
    Output:
    QUARTER PRODUCT SUM_CONFIG
    Q4-2006 P1 160
    Q4-2006 P2 997
    Q4-2007 P1 50
    Q4-2007 P2 60
    Q4-2008 70
    Q2-2007 P1 10
    Q2-2007 P2 20
    Q2-2008 70
    Q3-2007 P1 870
    Q3-2007 P2 970
    Q3-2008 70
    QUARTER PRODUCT SUM_CONFIG
    Q1-2007 P1 10
    Q1-2007 P2 20
    Q1-2008 P1 70
    Q1-2008 P2 70
    The query had not generated q2-2008,q3-2008,q4-2008 values [60]for P1...it had only generated q2-2008,q3-2008,q4-2008 values[70] for product P2.
    Can you please advise me.

    You can make up the data using the model clause:
    SQL> create table quarter_test3 (quarter, config, product)
      2  as
      3  select 'Q1-2007', 10, 'P1' from dual union all
      4  select 'Q2-2007', 10, 'P1' from dual union all
      5  select 'Q3-2007', 870, 'P1' from dual union all
      6  select 'Q4-2007', 50, 'P1' from dual union all
      7  select 'Q1-2008', 60, 'P1' from dual union all
      8  select 'Q4-2006', 160, 'P1' from dual union all
      9  select 'Q4-2006', 997, 'P2' from dual union all
    10  select 'Q1-2007', 60, 'P2' from dual union all
    11  select 'Q2-2007', 970, 'P2' from dual union all
    12  select 'Q3-2007', 20, 'P2' from dual union all
    13  select 'Q4-2007', 20, 'P2' from dual union all
    14  select 'Q1-2008', 70, 'P2' from dual
    15  /
    Tabel is aangemaakt.
    SQL> select 'Q' || to_char(mod(q,4) + 1) || '-' || to_char(trunc(q/4)) quarter
      2       , config
      3       , product
      4    from quarter_test3
      5   model
      6         partition by (product)
      7         dimension by (to_number(substr(quarter,4))*4 + to_number(substr(quarter,2,1)) - 1 q)
      8         measures (config)
      9         rules
    10         ( config[for q from 2006*4 + 3 to 2008*4 + 3 increment 1]
    11           = nvl(config[cv()],config[cv()-1])
    12         )
    13   order by product
    14       , q
    15  /
    QUARTER                                                                                CONFIG PR
    Q4-2006                                                                                   160 P1
    Q1-2007                                                                                    10 P1
    Q2-2007                                                                                    10 P1
    Q3-2007                                                                                   870 P1
    Q4-2007                                                                                    50 P1
    Q1-2008                                                                                    60 P1
    Q2-2008                                                                                    60 P1
    Q3-2008                                                                                    60 P1
    Q4-2008                                                                                    60 P1
    Q4-2006                                                                                   997 P2
    Q1-2007                                                                                    60 P2
    Q2-2007                                                                                   970 P2
    Q3-2007                                                                                    20 P2
    Q4-2007                                                                                    20 P2
    Q1-2008                                                                                    70 P2
    Q2-2008                                                                                    70 P2
    Q3-2008                                                                                    70 P2
    Q4-2008                                                                                    70 P2
    18 rijen zijn geselecteerd.Regards,
    Rob.

  • Native SQL query - Need help

    Hi All,
    We have a native SQL query accessing Oracle database(given below).
    Can anyone please let me know what this query is about and how can we fine tune the query?
    SELECT O.OBJECT_NAME ,
                   H.SID,
                   HS.MACHINE,
                   HS.PROCESS,
                   W.SID,
                   WS.MACHINE,
                   WS.PROCESS,
                   H.CTIME,
                   W.CTIME,
                   WS.ROW_WAIT_OBJ#,
                   WS.ROW_WAIT_FILE#,
                   WS.ROW_WAIT_BLOCK#,
                   WS.ROW_WAIT_ROW#,
                   HP.SPID,
                   WP.SPID
            FROM V$LOCK H, V$LOCK W, V$LOCK I, V$LOCK I2, ALL_OBJECTS O,
                 V$SESSION HS, V$SESSION WS, V$PROCESS HP, V$PROCESS WP
            WHERE   H.ID1 = W.ID1
            AND     H.SID <> W.SID
            AND     H.TYPE IN ('TX','DL')
            AND     H.REQUEST = 0
            AND     H.SID = I.SID
            AND     I.TYPE = 'TM'
            AND     I.ID1 = O.OBJECT_ID
            AND     I.ID1 = I2.ID1
            AND     W.SID = I2.SID
            AND     I2.TYPE = 'TM'
            AND     H.SID = HS.SID
            AND     W.SID = WS.SID
            AND     HS.PADDR = HP.ADDR
            AND     WS.PADDR = WP.ADDR
            INTO :EXCL_LOCK_WAITERS-OBJ_NAME   ,
                 :EXCL_LOCK_WAITERS-HOLDER_SID ,
                 :EXCL_LOCK_WAITERS-H_HOSTNAME ,
                :EXCL_LOCK_WAITERS-HOLDER_PID ,
                 :HOLDER_PID ,
                 :EXCL_LOCK_WAITERS-WAITER_SID ,
                 :EXCL_LOCK_WAITERS-W_HOSTNAME ,
                :EXCL_LOCK_WAITERS-WAITER_PID ,
                 :WAITER_PID ,
                 :EXCL_LOCK_WAITERS-HELD_SINCE ,
                 :EXCL_LOCK_WAITERS-WAITSSINCE,
                 :ROW_WAIT_OBJ,
                 :ROW_WAIT_FILE,
                 :ROW_WAIT_BLOCK,
                 :ROW_WAIT_ROW,
                 :H_PROCESS,
                 :W_PROCESS
          ENDEXEC
    Thanks in advance.
    Neethu Mohan

    Hi Neethu,
    It gives you an overwiew of blocking Oracle sessions.
    1. In general, the SQL checks Oracle sessions (SID's) that were requirering a DML lock ('TM') and now holding row locks (TX)  to prevent destructive interference of simultaneous conflicting DML or DDL operations. DML statements automatically acquire both table-level locks and row-level locks ('TX')  => holders
    It joins these with the sessions that are waiting of releasing the lock by the holders  => waiters.
    2. it retrieves the detail information wich  Oracle process , the object (table) , it's row , block  and file
    are affected by the locks.
    3. Normally, the locks are only hold for a short period of time. If you have blocking sessions it may be of a log running task (i.e. mass data update of a table) ; but it could also be a application bug due to improper handling of concurrent updates of the same object.
    4. Tuning
    V$tables are expensive to query: Why?
    v$ tables are generally Oracle memory structures.
    v$ tables are not read consistent.
    v$ tables require latches to access -- cannot modify and read memory at the same
    time.
    heavy access to v$ tables like this may cause some serious heavy duty contention.
    Especially if you self join V$lock several times.
    So the best would be to save the contents of V$LOCK in some table:
    Create table mylocks as select * from v$lock;
    Use that table for self-joining and joins to the other tables.
    You can also CTAS the other v$ tables to bypass the performance bottleneck while retrieving
    v$ directly.
    You can empty or drop the created tables any time for new data.
    Because you want to investigate only lock hold for a longert time  to copy the v$ memory structures into
    physical tables is not a disadvantage. You certainly will wait longer on finishing your query
    instead of copy them into the tables.
    Hope this helped
    yk

Maybe you are looking for

  • Podcast Problems [Zen Tou

    A few weeks ago I discovered the CBC Radio 3 podcast (http://www.cbcradio3.com/podcast/about.html). The first few downloads have been going well, but now when I try to transfer the files, Media Source says "Error: Unable to download file. The file fo

  • Need Help with ACTIONSCRIPT for Interactive Music Video

    I am trying to create an interactive music video in After Effects and Flash. The concept is that while the music video is taking place the user can  decorate the hair of the woman with any of the objects they select.   There will be predetermined ani

  • Plain White Border in Mozilla is Corrupted

    I used CSS to add a plain white thin border around an swf. It displayes properly in IE, but in Mozilla and Safari you only see the lower 5th of the border and the rest is missing. Here is the code: #gallery01 { border: thin solid #FFF;

  • Can i rename the Global Database Name

    Hi Seniors, i have installed the Oracle 10.2.3(10203_vista_w2k8_x86_production_db) in my VISTA Laptop. i have given the Global Database Name as orcsatya but i want to change to orasatya would u please tell how to proccess if it is..... thanks Seenuja

  • How can I delete Garage band projects?

    How can I delete Garage Band Projects? When GB opens, it takes time to scan for jampacs and then initializes. How can I skip that? I have no All My Files showing in Finder.