SQL - Analytical Query Question

Hi All,
I have a requirement for which I am trying to generate the output and I am not able to come up with good logic to solve this issue. I have been trying to solve this for some time now and am not able to figure out how.
I have posted a similar kind of post some time back but this is different to the original one and little more complex than my previous question. I have listed below the script to create a table and insert data.
DROP TABLE ITEMTABLE
CREATE TABLE ITEMTABLE
  ITEMTABLEID1           NUMBER(9) NOT NULL, 
  ITEMTABLEID2           NUMBER(9) NOT NULL,
  PARENTTABLEID          NUMBER(9),
  PARENTINFO          VARCHAR2(20), 
CONSTRAINT ITEMTABLE_PK PRIMARY KEY (ITEMTABLEID1,ITEMTABLEID2)          
Insert into ITEMTABLE values (19217,10245,19216,'PARENTINFO-1');
Insert into ITEMTABLE values (19217,10315,19216,'PARENTINFO-2' );
Insert into ITEMTABLE values (19217,10336,19216,'PARENTINFO-2' );
DROP TABLE FINANCE
CREATE TABLE FINANCE
  FINANCEKEY          NUMBER(9) NOT NULL,
  PARENTID1           NUMBER(9) NOT NULL, 
  PARENTID2           NUMBER(9) NOT NULL,  
  CONSTRAINT FINANCE_PK PRIMARY KEY (FINANCEKEY)
Insert into FINANCE values (8332, 19217,10245);
Insert into FINANCE values (8404, 19217, 10315);
Insert into FINANCE values (8425, 19217, 10336);
DROP TABLE ACCT
CREATE TABLE ACCT
  ACCTKEY             NUMBER(9)  NOT NULL,   
  FINANCEKEY          NUMBER(9),
  FLAG                VARCHAR2(1), 
  SOURCEKEY           NUMBER(9),
  CONSTRAINT ACCT_PK PRIMARY KEY (ACCTKEY)
Insert into ACCT values (9874, 8332, 'N',0);
Insert into ACCT values (9875, 8332, 'N',0 );
Insert into ACCT values (9982, 8404, 'Y', 9874);
Insert into ACCT values (9983, 8404, 'Y', 9875);
Insert into ACCT values (10008, 8425, 'N', 9982);
Insert into ACCT values (10009, 8425, 'Y', 9983);
SQL> With tempacct1 as
  2    (Select  I.ITEMTABLEID1,I.ITEMTABLEID2, AC.SOURCEKEY, NVL(AC.FLAG,'N') AS FLAG, AC.ACCTKEY
  3     FROM ITEMTABLE I,FINANCE F,ACCT AC
  4    where I.ITEMTABLEID1 = F.PARENTID1
  5      and I.ITEMTABLEID2 =  F.PARENTID2
  6    and F.FINANCEKEY = AC.FINANCEKEY
  7        and I.PARENTTABLEID = 19216
  8         ORDER BY  acctkey ASC
  9        )
10     SELECT  ITEMTABLEID1,ITEMTABLEID2,acctkey, flag ,SOURCEKEY
11     FROM    tempacct1;
ITEMTABLEID1 ITEMTABLEID2    ACCTKEY F  SOURCEKEY
       19217        10245       9874 N          0
       19217        10245       9875 N          0
       19217        10315       9982 Y       9874
       19217        10315       9983 Y       9875
       19217        10336      10008 N       9982
       19217        10336      10009 Y       9983
6 rows selected.
Desired Output -
ITEMTABLEID1 ITEMTABLEID2    ACCTKEY F  SOURCEKEY
       19217        10336      10008 N       9982
       19217        10336      10009 Y       9983The solution by Frank for my previous post few weeks back looks like this :-
SQL>    SELECT  sourcekey
  2  , flag
  3  , acctkey
  4  FROM (
  5       SELECT  ac.sourcekey
  6       ,     NVL (ac.flag, 'N') AS flag
  7       ,     ac.acctkey
  8       ,     RANK () OVER ( PARTITION BY  CASE
  9                         WHEN  sourcekey = 0
10             THEN  acctkey
11             ELSE  sourcekey
12                     END
13         ORDER BY      CASE
14                              WHEN  ac.flag = 'Y'
15                    THEN  1
16             ELSE  2
17                   END
18         ,   SIGN (sourcekey)
19                    ) AS rnk
20          FROM    itemtable i
21       ,     finance f
22       ,     acct ac
23         WHERE   i.itemtableid1  = f.parentid1
24         AND     i.itemtableid2  = f.parentid2
25       AND     f.financekey  = ac.financekey
26         AND     i.parenttableid  = 19216
27   )
28  WHERE rnk = 1;
SOURCEKEY F    ACCTKEY
      9874 Y       9982  -- Needs to be removed
      9875 Y       9983  -- Needs to be removed
      9982 N      10008  
      9983 Y      10009
Output Desired would be
ITEMTABLEID1 ITEMTABLEID2    ACCTKEY F  SOURCEKEY
       19217        10336      10008 N       9982
       19217        10336      10009 Y       9983
SQL> The slight change to the requirement is when we have sourcekey that is same as acctkey then only display the row which has max acctkey. So in this case, the last two row have a sourcekey of 9982, 9983 which is equal to acctkey of first two rows. So, we look for Max(Acctkey) which would be 10008 and 10009 and only display those.
This logic needs to be added on top of the existing logic. So I am not sure how it could be done.
I would really appreciate any help.
SQL> select * from v$version;
BANNER
Oracle Database 10g Release 10.2.0.4.0 - 64bit Production
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 - ProductionEdited by: ARIZ on Jun 16, 2010 7:56 PM

Hi,
This gets the right results from your sample data.
SELECT  ac.sourcekey
,       NVL (ac.flag, 'N') AS flag
,       ac.acctkey
FROM    itemtable     i
,          finance          f
,       acct          ac
WHERE   i.itemtableid1   = f.parentid1
AND     i.itemtableid2   = f.parentid2
AND     f.financekey     = ac.financekey
AND     i.parenttableid  = 19216
AND      ac.acctkey     NOT IN ( SELECT  sourcekey
                      FROM      acct
                     WHERE      sourcekey     IS NOT NULL     -- If needed
; I'm a little uncertain of your requirements, so I'm not sure how it will work on your real data.
At least in this new version of the problem, it looks like rows can be chained together, where the sourcekey of one row is the acctkey of the next row. If you want only the first row in each such chain, just look for the ones where the acctkey does not relate back to any sourcekey.
NOT IN is never TRUE if the subquery returns any NULLs. Unless sourcekey has a NOT NULL constraint, you'd better check for it in the NOT IN sub-query.

Similar Messages

  • SQL Query Question

    Hi,
    I am trying to filter my output from the query based on some conditions but not able to figure out how. May be I am just overlooking at the issue or is it something tricky.
    So, I have a query returning 4 rows of output out of which I need to filter the rows. I have created a table from the result of the query that I need to filter to make it simple. So below is my create table script and values that are obtained from my original query.
    CREATE TABLE TEMPACCT
      SOURCEKEY           NUMBER,
      FLAG                VARCHAR2(1),
      ITEMID              NUMBER(9)                 ,
      ITEMNAME            VARCHAR2(10)               ,
      ITEMKEY             NUMBER(9)                
    Insert into tempacct values (0, 'N', 100, 'ITEM1' , 9647);
    Insert into tempacct values (0, 'N', 200, 'ITEM2' , 9648);
    Insert into tempacct values (9648, 'N', 100, 'ITEM3' , 9813);
    Insert into tempacct values (9647, 'Y', 100, 'ITEM4' , 9812);
    SQL> select * from tempacct;
    SOURCEKEY F     ITEMID ITEMNAME      ITEMKEY
             0 N        100 ITEM1            9647
             0 N        200 ITEM2            9648
          9648 N        100 ITEM3            9813
          9647 Y        100 ITEM4            9812
    SQL> Tempacct table is the table created from the resultset of my original query.
    So from the above output, what I need is 3 rows. The logic to filter out the row is - If any of the row thathas sourcekey that is same as Itemkey in any of the 4 rows and flag is Y then remove the row which have flag =N and only display the one with Falg = Y.
    Ok, so, in this case the desired output would be
    SOURCEKEY F     ITEMID ITEMNAME      ITEMKEY
             0 N        200 ITEM2            9648
          9648 N        100 ITEM3            9813
          9647 Y        100 ITEM4            9812So here we compared between the first row and the fourth row, and since the sourcekey in fourth row is same as itemkey in first row and Flag is 'Y' for fourth row, we keep 4th row and remove the first row since the flag is 'N'. (and sourcekey is 0. the row that gets removed will always have sourcekey =0) .
    SQL> select * from v$version;
    BANNER
    Oracle Database 10g Release 10.2.0.4.0 - 64bit Production
    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 - ProductionAppreciate your help.

    Hi,
    ARIZ wrote:
    Although the original question is already been answered, I had another small modification to the same question and also seeking some clarification. I do not want to open a new thread just for a similar question.I think you'll get better replies faster if you do start a new thread.
    Not counting this one, there have been 13 replies to this thread. Not many people who havn't already been participating in this thread are going to start reading a thread with 13 replies. Those who do are going to waste a lot of time reading about issues that have already been resolved, and the are likely to understand the remaining issues incorrectly.
    I have been following the thread from the beginnning, and I'm starting to get confused about what the unresolved issues are.
    I believe there are two things you still need:
    (1) An explanation of the solution I posted yesterday, involving the analytic COUNT function.
    (2) A solution for a new problem involving the same tables
    If I got that wrong, start a new thread, asking just what you need to know. Copy any relevant parts (like the CREATE TABLE and INSERT statements) from this thread. You can include a link to this thread, but do your best to make sure people don't have to use it.
    I realize that's more work for you, but getting the best results, and getting them quickly, sometimes does require more work.
    <h2>(1) An explanation of the solution I posted yesterday, involving the analytic COUNT function.</h2>
    ARIZ wrote:
    Hi Frank,
    Just out of curiosity, I was trying to understand the Count analytical function that you have used in the solution.
                    COUNT ( CASE
                                 WHEN  ac.flag = 'Y'
                           THEN  1
                             END
                        ) OVER ( PARTITION BY  CASE
                                                   WHEN  sourcekey = 0
                                       THEN  acctkey
                                       ELSE  sourcekey
                                               END
                                  )     AS y_cntSo what I am thinking is, this would first partition the row with acctkey ( where sourcekey =0) and sourcekey and then within that partition, it will check whether ac.flag = Y or not, if it is 'Y' then it would return count as 1 else 0. Am I correct? In the mean time I am also reading the tutorials on Count() analytical query. I'm not sure I understand your explanation.
    This is not partitioning first by x, and then by y. There is only one expression in the PARTITION BY clause. Most often, a PARTITION BY clause refers to some column in the table, for example:
    SELECT  ename
    ,       job
    ,       sal
    ,       AVG (sal) OVER (PARTITION BY job)  AS avg_sal_for_job
    FROM    scott.emp;This divides the result set into mutually exclusive parts; there will be as many such parts as there are distinct values for the PARTITION BY column. In the simple query above, if there happen to be 5 different values for job, you will get 5 independent averages.
    In your problem, there is no one column that defines a partition. That is, these two rows belong to the same partition:
    . SOURCEKEY F   ACCTKEY
             0 N       9647
          9647 Y       9812even though none of the 3 columns are the same. We could create a view that had a single column, telling to which partition each row belonged, like this:
    . SOURCEKEY F   ACCTKEY PART_NUM
             0 N       9648     9648
             0 N       9647         9647
          9648 N       9813         9648
          9647 Y       9812         9647where part_num is the result of a CASE expression:
    CASE
        WHEN  sourcekey = 0
        THEN  acctkey
        ELSE  sourcekey
    ENDWe could then use that new column, part_num, in a (very simple) PARTITION BY clause. But there is no need to create a view, even an in-line view, for that: we can (and I did) use the CASE expression directly in a (not so simple) PARTITION BY clause.
    Why did I use COUNT? The important thing about each partition is whether or not it includes any rows with flag='Y'. I don;t know of any function that directly answers that question. There are lots of ways to get the correct answer, but I think the one that corresponds most closely to the question we really want to ask:
    "Do any rows have flag='Y'?" is
    "How many rows have flag='Y'?"
    The analytic function COUNT (x) returns a number (possibly 0) of rows in the partition where x is not NULL. So, as the argument to COUNT, I used
    CASE
        WHEN  ac.flag = 'Y'
        THEN  1
    --  ELSE  NULL          -- I did not explicitly say this, but it is the default
    ENDwhich returns either
    (a) the literal number 1 or
    (b) NULL
    Instead of the literanl number 1, I could have used any literal or expression, of any data type, that is not NULL). all that matters is we produce something non-NULL for COUNT to count.
    <h2>(2) A solution for a new problem involving the same tables</h2>
    Also, I was trying to modify this query to fit my other similar requirement where I would need following output
    Original output:
    SOURCEKEY F    ACCTKEY
    0 N       9648
    0   N      9647
    9648 N       9813
    9647 Y       9812
    So, the query should be smart enough to return only the last two rows where sourcekey >0 which is
    SOURCEKEY F    ACCTKEY
    9648 N       9813
    9647 Y       9812
    And In case there are only first two 2 rows in the table then , it should return only those two row and not check for sourcekey > 0 which would be .
    SOURCEKEY F    ACCTKEY
    0 N       9648
    0   N      9647 Is it something that I should be using analytical function to solve this requirement. I am trying to accomplish this new requirement.If I understand this problem correctly, it does indeed involve mutually exclusive divisions, but in this problem, the divisions correspond more closely to a single column in the table. We want to divide the table into two mutually exclusive groups:
    (A) rows where soucekey > 0, and
    (B) rows where sourcekey = 0
    We could do that with a CASE expression, but there happens to be a built-in function that works very nicely.
    SIGN (sourcekey) returns
    (A) 1 if sourcekey > 0, and
    (B) 0 if sourcekey = 0
    But what do we want to do with those divisions? We want to display rows only from the "best" of those divisions, where division (A) is coinsidered "better" than division (B). That is, if there are any rows in division (A), then we want to display only rows in division (A), but if there are no rows in division (A), then (and only then) we want to display rows in divison (B).
    This is an example of a Top-N Query , where we want to display N items from the top of an ordered list. A typical top-N query uses an analytic function (either ROW_NUMBER, RANK or DENSE_RANK, depending on how we want to handle ties) to assign numbers to each row (lower numbers for the "better" rows), and then uses "WHERE f <= n" to display only the n "best" ones. (A special case, though a very common one, is where N=1, that is, we're only interested in the row (or rows, if there happens to be a tie) with the "best" value. In this case, most people find it cleare to say "WHERE f = 1" ratehr than "WHERE f <= 1". Your problem is an exmple ot that special case.)
    SELECT  sourcekey
    ,     flag
    ,     acctkey
    FROM     (
             SELECT  ac.sourcekey
             ,         NVL (ac.flag, 'N')     AS flag
             ,         ac.acctkey
             ,         DENSE_RANK () OVER (ORDER BY  SIGN (sourcekey)     DESC)     AS division_num
                FROM    itemtable     i
             ,         finance     f
             ,         acct     ac
               WHERE   i.itemtableid1      = f.parentid1
               AND         i.itemtableid2      = f.parentid2
             AND         f.financekey      = ac.financekey
               AND         i.parenttableid      = 19063
    WHERE     division_num     = 1
    ;Notice I talked about "mutually exclusiive *divisions* " above, not "mutually exclusive *partitions* ".
    There is no PARTITION BY in the analytic clause above. PARTITION BY means we want a separate, independent caluclation for each partition. Here, we want one single numbering for the entire result set.
    We want all rows that tie for the "best" to be numbered 1, so we have to use DENSE_RANK (or RANK) rather than ROW_NUMBER.

  • Reg: SQL select Query in BPEL process flow

    <p>
    Hi,
    I am suppose to execute a SQL select query (in BPEL Process flow) as mention below in JDeveloper using Database adapter.
    </p>
    <p>
    SELECT LENGTH, WIDTH, HEIGHT, WEIGHT,
    </p>
    <p>
    LENGTH*WIDTH* HEIGHT AS ITEM_CUBE
    </p>
    <p>
    FROM CUBE
    </p>
    <p>
    WHERE ITEM= &lt;xyz&gt;
    </p>
    <p>
    AND OBJECT= (SELECT CASE_NAME FROM CUBE_SUPPLIER WHERE ITEM=&lt;xyz&gt; AND SUPP_IND = &lsquo;Y')
    <strong>Now my question is:
    1.</strong> What does this "*" refer to in the query and how can I retrieve the value of LENGTH*WIDTH* HEIGHT from the query where LENGTH,WIDTH and HEIGHT are the individual field in the table.
    2.What does this " AS" refer to? If " ITEM_CUBE " is the alies for the table name "ITEM" to retrieve the value, then query shoud be evaluated as
    </p>
    <p>
    SELECT LENGTH, WIDTH, HEIGHT, WEIGHT,
    </p>
    <p>
    LENGTH*WIDTH* HEIGHT AS ITEM_CUBE
    </p>
    <p>
    FROM CUBE
    </p>
    <p>
    WHERE <strong>ITEM_CUBE.ITEM</strong>= &lt;xyz&gt;
    </p>
    <p>
    AND <strong>ITEM_CUBE.OBJECT</strong>= (SELECT CASE_NAME FROM CUBE_SUPPLIER WHERE ITEM=&lt;xyz&gt; AND SUPP_IND = &lsquo;Y')
    Is my assumption correct?
    Please suggest asap.
    Thanks...
    </p>
    <p>
    </p>

    Hi
    Thank for your reply!
    I have a nested select query which performs on two different table as shown below:
    <p>
    SELECT LENGTH, WIDTH, HEIGHT, WEIGHT,
    </p>
    <p>
    LENGTH*WIDTH* HEIGHT AS ITEM_CUBE
    </p>
    <p>
    FROM CUBE
    </p>
    <p>
    WHERE ITEM= &lt;abc&gt;
    </p>
    <p>
    AND OBJECT= (SELECT NAME FROM SUPPLIER WHERE ITEM=&lt;Item&gt; AND SUPP_IND = &lsquo;Y')
    I am using DB adapter of Oracle JDeveloper in BPEL process flow, where I can able to select only one master table in DB adapter say SUPPLIER and its attributes at a time.But as per my requirment I need to select both the table (CUBE and SUPPLIER) in a single adapter to execute my query.
    It can be achievable by using two DB adapter , One to execute the nested query and another to execute the main qyery considering value of nested query as a parameter.But I want to achieve it by using a single one.
    Am I correct with my concept?
    Please suggest how to get it ?
    </p>
    Edited by: user10259700 on Oct 23, 2008 12:17 AM

  • Sql server query

    sql server query to rearrange the rows after inserting the rows in a table

    You want to re-arrange the data physically?!!! Why? I believe its something impossible other than having a clustered key(there could be some strange ways of doing it) and a thing that should not worry about. Always there is a ORDER BY CLAUSE to order your
    data while retrieving 
    Satheesh
    My Blog |
    How to ask questions in technical forum

  • Get only last level in SQL Hierarchy Query

    Hi,
    How to get only the last level in Oracle SQL Hierarchy Query?
    Thanks

    Hi,
    1007372 wrote:
    Hi,
    How to get only the last level in Oracle SQL Hierarchy Query?Depending on your requirements:
    WHERE   CONNECT_BY_ISLEAF  = 1 
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and also post the results you want from that data.
    Explain, using specific examples, how you get those results from that data.
    If you can show what you want to do using commonly available tables (such as scott.emp, which contains a hierarchy), then you don't need to post any sample data; just the results and the explanation.
    Always say which version of Oracle you're using (e.g., 11.2.0.2.0). This is always important, but especially so with CONNECT BY queries, because every version since Oracle 7 has had significant improvements in this area.
    See the forum FAQ {message:id=9360002}

  • SQL Azure - query with row_number() executes slow if columns with nvarchar of big size are included

    I am linking my question from Stack Overflow here. The link: http://stackoverflow.com/questions/27943913/sql-azure-query-with-row-number-executes-slow-if-columns-with-nvarchar-of-bi
    Appreciate your help!
    Gorgi

    Hi,
    Thanks for posting here.
    I suggest you to check this link and optimize your query on sql azure.
    http://www.sqlusa.com/articles/query-optimization/
    http://sqlblog.com/blogs/paul_white/archive/2011/02/23/Advanced-TSQL-Tuning-Why-Internals-Knowledge-Matters.aspx
    Also check this blog which had similar issue.
    https://social.msdn.microsoft.com/Forums/en-US/c1da08b4-265d-4ec8-a252-8d7090234e3e/simple-select-query-takes-long-time-to-execute-with-nvarchar-columns?forum=transactsql
    Girish Prajwal

  • Oracle SQL Select query takes long time than expected.

    Hi,
    I am facing a problem in SQL select query statement. There is a long time taken in select query from the Database.
    The query is as follows.
    select /*+rule */ f1.id,f1.fdn,p1.attr_name,p1.attr_value from fdnmappingtable f1,parametertable p1 where p1.id = f1.id and ((f1.object_type ='ne_sub_type.780' )) and ( (f1.id in(select id from fdnmappingtable where fdn like '0=#1#/14=#S0058-3#/17=#S0058-3#/18=#1#/780=#5#%')))order by f1.id asc
    This query is taking more than 4 seconds to get the results in a system where the DB is running for more than 1 month.
    The same query is taking very few milliseconds (50-100ms) in a system where the DB is freshly installed and the data in the tables are same in both the systems.
    Kindly advice what is going wrong??
    Regards,
    Purushotham

    SQL> @/alcatel/omc1/data/query.sql
    2 ;
    9 rows selected.
    Execution Plan
    Plan hash value: 3745571015
    | Id | Operation | Name |
    | 0 | SELECT STATEMENT | |
    | 1 | SORT ORDER BY | |
    | 2 | NESTED LOOPS | |
    | 3 | NESTED LOOPS | |
    | 4 | TABLE ACCESS FULL | PARAMETERTABLE |
    |* 5 | TABLE ACCESS BY INDEX ROWID| FDNMAPPINGTABLE |
    |* 6 | INDEX UNIQUE SCAN | PRIMARY_KY_FDNMAPPINGTABLE |
    |* 7 | TABLE ACCESS BY INDEX ROWID | FDNMAPPINGTABLE |
    |* 8 | INDEX UNIQUE SCAN | PRIMARY_KY_FDNMAPPINGTABLE |
    Predicate Information (identified by operation id):
    5 - filter("F1"."OBJECT_TYPE"='ne_sub_type.780')
    6 - access("P1"."ID"="F1"."ID")
    7 - filter("FDN" LIKE '0=#1#/14=#S0058-3#/17=#S0058-3#/18=#1#/780=#5#
    8 - access("F1"."ID"="ID")
    Note
    - rule based optimizer used (consider using cbo)
    Statistics
    0 recursive calls
    0 db block gets
    0 consistent gets
    0 physical reads
    0 redo size
    0 bytes sent via SQL*Net to client
    0 bytes received via SQL*Net from client
    0 SQL*Net roundtrips to/from client
    0 sorts (memory)
    0 sorts (disk)
    9 rows processed
    SQL>

  • Sql select query problem

    hi friends,
    i've a view called "risk_efforts" with fields user_id,user_name,wknd_dt,week_day,prod_efforts,unprod_efforts.
    Name Type
    ROW_ID NUMBER
    USER_ID VARCHAR2(14)
    USER_NAME VARCHAR2(50)
    WKND_DT VARCHAR2(8)
    WEEK_DAY VARCHAR2(250)
    PROD_EFFORTS NUMBER
    UNPROD_EFFORTS NUMBER
    data is like this:
    when there is some data in prod_efforts, unprod_efforts will be null
    when there is some data in unprod_efforts, prod_efforts will be null
    for example:
    USER_ID     USER_NAME     WKND_DT     WEEK_DAY     PROD_EFFORTS     UNPROD_EFFORTS
    G666999     GTest     20100403     TUE     null 3
    G666999     GTest     20100403     TUE     14     null
    now i want to combine these 2 rows into 1 row i.e o/p should be like this
    USER_ID     USER_NAME     WKND_DT     WEEK_DAY     PROD_EFFORTS     UNPROD_EFFORTS
    G666999     GTest     20100403     TUE     14 3
    i've tried all combinations but couldn't get the query. Please help me with the exact SQL select query.
    thanks,
    Girish

    Welcome to the forum.
    First read this:
    Urgency in online postings
    Secondly, it's always helpful to provide the following:
    1. Oracle version (SELECT * FROM V$VERSION)
    2. Sample data in the form of CREATE / INSERT statements.
    3. Expected output
    4. Explanation of expected output (A.K.A. "business logic")
    5. Use \ tags for #2 and #3. See FAQ (Link on top right side) for details.
    You have provided #3 and #4. However with no usable form of sample data forum members will often not respond as quickly as they could if you provided #2.
    I'm just wagering a guess here but what about this:SELECT ROW_ID
    , USER_ID
    , WKND_DT
    , WEEK_DAY
    , MAX(PROD_EFFORTS) AS PROD_EFFORTS
    , MAX(UNPROD_EFFORTS) AS UNPROD_EFFORTS
    FROM RISK_EFFORTS
    GROUP BY ROW_ID
    , USER_ID
    , WKND_DT
    , WEEK_DAY                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • How to capture all the rows returned from a sql select query in CPO

    Hi,
      I am executing an sql select query which returns multiple rows. I need to capture the values of each row to specific variables. How do I proceed.
    Thanks,
    Swati

    The select activities  ("Select from Oracle," Select from SQL Server," etc.) against database already return tables.  Use one of the database adapters to do your select, and it will already be in a table form.  Just put your query in the select and identify the columns in your result table. The online help or the database adapter guides in the product documentation can help.

  • From SharePoint Content Database, Using SQL-Server Query how to fetch the 'Document GUID' based on 'Content Type'

    I want to get all the documents based on content type using SQL Server Query. I know that, querying the content database without using API is not advisable, but still i want to perform this action through SQL Server Query. Can someone assist ?

    You're right, it's not advisable, may result in corruption of your databases and might impact performance and stability. But assuming you're happy to do that then it is possible.
    Before you go down that route, have you considered using something more safe like PowerShell? I've seen a script exactly like the one you describe and it would take far less time to do it through PS than it would through SQL.

  • Sql developer query window corrupting on scroll

    Hi there
    I have a weird error - when I scroll in my SQL developer query window (tab) the text corrupts and only comes back if I click in the window somewhere or save. Has anyone else seen this? I'm on version 1.5.5 and don't really want to upgrade to the latest as I don't like the new layout (no dbmsoutput etc in the results window)
    Cheers, Kate

    sorted it by adding a line AddVMOption -Dsun.java2d.noddraw=true to the sqldeveloper.conf file, as per thread SQL Editor not refreshing after scroll on Windows Vista

  • Embedded SQL against Oracle Question

    Software: Forte 3.0.J.
    Server Platform: HPUX 10.2
    Database: Oracle
    Problem Description: During the course of development, I ran into a
    problem using multiple columns in an sql UPDATE/SET statement. I was trying
    to update a.COLUMN_1 and a.COLUMN_2, which constitute part of the primary
    key of associative TABLE_A (a). In order for me to make the update, I
    needed to use the existing value of a.COLUMN_1 to lookup the new b.COLUMN_1
    in TABLE_B (b). Where a.COLUMN_1 = b.RELATED_COLUMN_1, I am able to find
    each b.COLUMN_2 that correspond to each a.COLUMN_2.
    I was able to resolve the issue by separating the two columns so
    that each had it's own select statement. Theoretically, it appears that
    this shouldn't work, because the SET statement for a.COLUMN_1 would cause
    the a.COLUMN_1 reference in the select statement of a.COLUMN_2 to be
    overwritten.
    In spite of this, I tried it, and it worked. I would like to
    understand why the sql works, and how sql actually executes the statement.
    Here is the sql:
    UPDATE TABLE_A a
    SET a.COLUMN_1 =
    (SELECT DISTINCT b1.COLUMN_1
    FROM TABLE_B b1
    WHERE b1.RELATED_CASE_ID =
    a.COLUMN_1 AND
    b1.RELATED_COLUMN_TYPE_CD = 'NEPHI'),
    a.COLUMN_2=
    (SELECT DISTINCT b2.COLUMN_2
    FROM TABLE_B b2
    WHERE b2.RELATED_COLUMN_1=
    a.COLUMN_1 AND
    b2.RELATED_COLUMN_TYPE_CD = 'NEPHI' AND
    b2.RELATED_COLUMN_2= a.COLUMN_2)
    WHERE a.COLUMN_1 = 100
    The table structure is as follows:
    TABLE_A: (primary keys are bolded) This is an associative table.
    Column_1 and Column_2 comprise the pk of one table; Column_3 and Column_4
    comprise the pk of another table. Assume that the Column_1 and Column_2
    values replacing the original values already exist in the parent table of
    which they form the pk).
    COLUMN_1
    COLUMN_2
    COLUMN_3
    COLUMN_4
    COLUMN_5
    TABLE_B: (primary keys are bolded) This is a reference table.
    COLUMN_1
    COLUMN_2
    RELATED_COLUMN_1
    RELATED_COLUMN_2
    RELATED_COLUMN_TYPE_CD
    To unsubscribe, email '[email protected]' with
    'unsubscribe forte-users' as the body of the message.
    Searchable thread archive <URL:http://pinehurst.sageit.com/listarchive/>

    If you do an explain plan or set autotrace on against this update statement,
    you'll find that the select operations are actually executed first by Oracle
    - I believe because of the nature of the transaction. Thus, no problem.
    Brian Wilson
    U.S. Bancorp Piper Jaffray
    [email protected]
    Phone (612) 342-5682
    From: David Pettit[SMTP:[email protected]]
    Reply To: David Pettit
    Sent: Friday, April 30, 1999 1:58 PM
    To: '[email protected]'
    Subject: Embedded SQL against Oracle Question
    Software: Forte 3.0.J.
    Server Platform: HPUX 10.2
    Database: Oracle
    Problem Description: During the course of development, I ran into a
    problem using multiple columns in an sql UPDATE/SET statement. I was
    trying
    to update a.COLUMN_1 and a.COLUMN_2, which constitute part of the primary
    key of associative TABLE_A (a). In order for me to make the update, I
    needed to use the existing value of a.COLUMN_1 to lookup the new
    b.COLUMN_1
    in TABLE_B (b). Where a.COLUMN_1 = b.RELATED_COLUMN_1, I am able to find
    each b.COLUMN_2 that correspond to each a.COLUMN_2.
    I was able to resolve the issue by separating the two columns so
    that each had it's own select statement. Theoretically, it appears that
    this shouldn't work, because the SET statement for a.COLUMN_1 would cause
    the a.COLUMN_1 reference in the select statement of a.COLUMN_2 to be
    overwritten.
    In spite of this, I tried it, and it worked. I would like to
    understand why the sql works, and how sql actually executes the statement.
    Here is the sql:
    UPDATE TABLE_A a
    SET a.COLUMN_1 =
    (SELECT DISTINCT b1.COLUMN_1
    FROM TABLE_B b1
    WHERE b1.RELATED_CASE_ID =
    a.COLUMN_1 AND
    b1.RELATED_COLUMN_TYPE_CD = 'NEPHI'),
    a.COLUMN_2=
    (SELECT DISTINCT b2.COLUMN_2
    FROM TABLE_B b2
    WHERE b2.RELATED_COLUMN_1=
    a.COLUMN_1 AND
    b2.RELATED_COLUMN_TYPE_CD = 'NEPHI' AND
    b2.RELATED_COLUMN_2= a.COLUMN_2)
    WHERE a.COLUMN_1 = 100
    The table structure is as follows:
    TABLE_A: (primary keys are bolded) This is an associative table.
    Column_1 and Column_2 comprise the pk of one table; Column_3 and Column_4
    comprise the pk of another table. Assume that the Column_1 and Column_2
    values replacing the original values already exist in the parent table of
    which they form the pk).
    COLUMN_1
    COLUMN_2
    COLUMN_3
    COLUMN_4
    COLUMN_5
    TABLE_B: (primary keys are bolded) This is a reference table.
    COLUMN_1
    COLUMN_2
    RELATED_COLUMN_1
    RELATED_COLUMN_2
    RELATED_COLUMN_TYPE_CD
    To unsubscribe, email '[email protected]' with
    'unsubscribe forte-users' as the body of the message.
    Searchable thread archive <URL:http://pinehurst.sageit.com/listarchive/>
    Nondeposit investment products are not insured by the FDIC, are
    not deposits or other obligations of or guaranteed by U.S. Bank
    National Association or its affiliates, and involve investment
    risks, including possible loss of the principal amount invested.
    Past performance does not guarantee future results. We consider
    our sources reliable. Accuracy and completeness are not guaranteed.
    Information is subject to change. Transactional details should not
    be relied on for tax purposes and do not supersede normal trade
    confirmations or statements. Messaging outside U.S. jurisdictions
    from U.S. Bancorp Piper Jaffray to non-institutional parties is not
    intended for solicitation purposes.
    Electronic mail sent through the Internet is not secure. We will
    not accept time-sensitive, action-oriented messages, transaction
    orders, fund transfer instructions or check stop payments
    electronically.
    If you are not the intended recipient, notify the Sender. This
    information is intended only for the person named above and for
    the purposes indicated. Do not distribute this message without
    written consent of the author. Non-business opinions may not
    reflect opinions of U.S. Bancorp Piper Jaffray and its affiliates.
    U.S. Bancorp Piper Jaffray and its affiliates reserve the right to
    monitor all e-mail.
    Securities products and services are offered through
    U.S. Bancorp Piper Jaffray Inc., member SIPC and NYSE, Inc.,
    a subsidiary of U.S. Bancorp.
    To unsubscribe, email '[email protected]' with
    'unsubscribe forte-users' as the body of the message.
    Searchable thread archive <URL:http://pinehurst.sageit.com/listarchive/>

  • PL/SQL spatial query will not compile.

    I have a PL/SQL spatial query that will not compile, but the equivalent SQLPlus query works fine. I.e. (convert decimal degrees to degrees,minutes,seconds)
    Any thoughts much appreciated....
    THIS WORKS in SQLPlus
    select
    decode(rownum,1,decode(sign(b.column_value),-1,'W','E'),2,decode(sign(b.column_v
    alue),-1,'S','N'))&#0124; &#0124;
    to_char(abs(trunc(b.column_value,0)),'999')
    &#0124; &#0124;to_char(abs(trunc((b.column_value - trunc(b.column_value,0)) * 60,0)),'99')
    &#0124; &#0124;to_char(abs(
    (((b.column_value - trunc(b.column_value,0)) * 60) - trunc((b.column_value - tru
    nc(b.column_value,0)) * 60,0)) * 60
    ),'99.99')
    from route_location a, table(a.line.sdo_ordinates) b
    where a.route_adms_id = 13820370
    and record_seq_num = 26
    and rownum < 3
    BUT THIS DOES NOT
    ADMS>create or replace procedure PKG_route_loc_latlong_ins
    2 (iADMS_ID in INTEGER, iRSN in INTEGER,
    3 vcLAT out VARCHAR2, vcLONG out VARCHAR2) as
    4 cursor c1 is
    5 select decode(rownum,1,decode(sign(b.column_value),-1,'W','E'),
    6 2,decode(sign(b.column_value),-1,'S','N'))
    7 &#0124; &#0124;to_char(abs(trunc(b.column_value,0)),'999')
    8 &#0124; &#0124;to_char(abs(trunc((b.column_value - trunc(b.column_value,0)) * 60,0)),
    '99')
    9 &#0124; &#0124;to_char(abs(
    10 (((b.column_value - trunc(b.column_value,0)) * 60) -
    11 trunc((b.column_value - trunc(b.column_value,0)) * 60,0)) * 60
    12 ),'99.99')
    13 from route_location a, table(a.line.sdo_ordinates) b
    14 where a.route_adms_id = iADMS_ID
    15 and a.record_seq_num = iRSN
    16 and rownum < 3;
    17 BEGIN
    18 open c1;
    19 fetch c1 into vcLONG;
    20 fetch c1 into vcLAT;
    21
    22 EXCEPTION
    23 when others then
    24 vcLAT := 'ERROR';
    25 RAISE_APPLICATION_ERROR(-20002,
    26 'XXXXXXXXXXXXXX ');
    27
    28 END pkg_route_loc_latlong_ins;
    29 /
    Warning: Procedure created with compilation errors.
    ADMS>
    ADMS>show errors
    Errors for PROCEDURE PKG_ROUTE_LOC_LATLONG_INS:
    LINE/COL ERROR
    5/5 PL/SQL: SQL Statement ignored
    5/12 PLS-00320: the declaration of the type of this expression is
    incomplete or malformed
    5/12 PLS-00320: the declaration of the type of this expression is
    incomplete or malformed
    13/34 PLS-00201: identifier 'A.LINE' must be declared
    19/5 PL/SQL: SQL Statement ignored
    20/5 PL/SQL: SQL Statement ignored
    null

    try a
    FOR UPDATE OF ID NOWAIT;where ID is the name of a column in the table.

  • How to tune the performance of Oracle SQL/XML query?

    Hi all,
    I am running Oracle 9i and like to run the following Oracle SQL/XML query. It takes about 3+ hour and still not finish. If I get rid all the XML stuffs it only take minutes to run. Does anybody know how to what's the reason of this slow and how to tune it?
    SELECT XMLElement("CUSTOMER",
    XMLForest(C_CUSTKEY "C_CUSTKEY", C_NAME "C_NAME", C_ADDRESS "C_ADDRESS", C_PHONE "C_PHONE", C_MKTSEGMENT "C_MKTSEGMENT", C_COMMENT "C_COMMENT"),
    (SELECT XMLAgg(XMLElement("ORDERS",
    XMLForest(O_ORDERKEY "O_ORDERKEY", O_CUSTKEY "O_CUSTKEY", O_ORDERSTATUS "O_ORDERSTATUS", O_ORDERPRIORITY "O_ORDERPRIORITY", O_CLERK "O_CLERK", O_COMMENT "O_COMMENT"),
    (SELECT XMLAgg(XMLElement("LINEITEM",
    XMLForest(L_ORDERKEY "L_ORDERKEY", L_RETURNFLAG "L_RETURNFLAG", L_LINESTATUS "L_LINESTATUS", L_SHIPINSTRUCT "L_SHIPINSTRUCT", L_SHIPMODE "L_SHIPMODE", L_COMMENT "L_COMMENT")
    FROM LINEITEM
    WHERE LINEITEM.L_ORDERKEY = ORDERS.O_ORDERKEY)
    FROM ORDERS
    WHERE ORDERS.O_CUSTKEY = CUSTOMER.C_CUSTKEY)
    FROM CUSTOMER ;
    Thanks very much in advance for your time,
    Jinghao Liu

    ajallen wrote:
    Why not something more like
    SELECT *
    FROM fact1 l,
    FULL OUTER JOIN fact1 d
    ON l.company = d.company
    AND l.transactiontypeid = 1
    AND d.transactiontypeid = 2;
    Because this is not an equivalent of the original query.
    drop table t1 cascade constraints purge;
    drop table t2 cascade constraints purge;
    create table t1 as select rownum t1_id from dual connect by level <= 5;
    create table t2 as select rownum+2 t2_id from dual connect by level <= 5;
    select * from (select * from t1 where t1_id > 2) t1 full outer join t2 on (t1_id = t2_id);
    select * from t1 full outer join t2 on (t1_id = t2_id and t1_id > 2);
         T1_ID      T2_ID
             3          3
             4          4
             5          5
                        6
                        7
         T1_ID      T2_ID
             1
             2
             3          3
             4          4
             5          5
                        6
                        7

  • How to perf tune Oracle SQL/XML query?

    Hi all,
    I am using Oracle 9i and like to run the following Oracle SQL/XML query. It takes about 3+ hour and still not finish. If I get rid all the XML stuffs it only take minutes to run. Does anybody know how to what's the reason of this slow and how to tune it?
    SELECT XMLElement("CUSTOMER",
    XMLForest(C_CUSTKEY "C_CUSTKEY", C_NAME "C_NAME", C_ADDRESS "C_ADDRESS", C_PHONE "C_PHONE", C_MKTSEGMENT "C_MKTSEGMENT", C_COMMENT "C_COMMENT"),
    (SELECT XMLAgg(XMLElement("ORDERS",
    XMLForest(O_ORDERKEY "O_ORDERKEY", O_CUSTKEY "O_CUSTKEY", O_ORDERSTATUS "O_ORDERSTATUS", O_ORDERPRIORITY "O_ORDERPRIORITY", O_CLERK "O_CLERK", O_COMMENT "O_COMMENT"),
    (SELECT XMLAgg(XMLElement("LINEITEM",
    XMLForest(L_ORDERKEY "L_ORDERKEY", L_RETURNFLAG "L_RETURNFLAG", L_LINESTATUS "L_LINESTATUS", L_SHIPINSTRUCT "L_SHIPINSTRUCT", L_SHIPMODE "L_SHIPMODE", L_COMMENT "L_COMMENT")
    FROM LINEITEM
    WHERE LINEITEM.L_ORDERKEY = ORDERS.O_ORDERKEY)
    FROM ORDERS
    WHERE ORDERS.O_CUSTKEY = CUSTOMER.C_CUSTKEY)
    FROM CUSTOMER ;
    Thanks very much in advance for your time,
    Jinghao Liu

    Please post this message at:
    Forums Home » Oracle Technology Network (OTN) » Products » Database » XML DB

Maybe you are looking for

  • Remote Function Module problem

    Hi Experts, I have written a Se38 progarm to execute a remote function module, so as to send some data out of the system. The receiving system is an XI system. Pls see below the code and the load at the XI end, I donno why and what mistake am I doing

  • No response due to long running Action classes

    Hi, I have a small issue in my application. Please help providing the solution for the following problematic scenario faced in my application. My project is generally a report generation project, arch used: our-own architecture(similar to struts) Ser

  • Microsoft Office Home and Student 2007 trial

    5 days ago I purchased a Toshiba Satelilte 300 laptop, and have a 60 day trial for Microsoft Office Home and Student 2007 but am experiencing problems with installing it. I have obtained a Trial Activation Key and entered it when prompted; when the c

  • Problems with email, Macbook Pro, Yosemite

    Keep getting knocked out of email. Different errors, mostly cannot connect to server. Per Apple's mail support page. One of the settings should be Password. When I change to password in settings, it keeps switching to MD5 Challenge -Response. Could t

  • Updating materials issued for  production thru movement type

    hi we are using repetitive manufacturing scenario, and we are using back flush,  how to find out the materials issued for production thru movement types, from which tables can i get the data from AUFK  i am getting the movement types and the order nu