Query question ( I am having a senior moment)

I have 2 talbes
Table One
Key Value
A 1
A 2
A 3
A 4
B 1
B 2
B 3
Table Two
Key Value
A A
A B
B A
B B
B C
B D
B E
I want to return :
Key Value1 Value2
A 1 A
A 2 B
A 3
A 4
B 1 A
B 2 B
B 3 C
B D
B E
How can I write this query ??
Thanks..

In deference to your seniority :P, I won't point out that you neglected to tell us how table one value joins to table two value, so you'll have to adapt thi sto meet your own needs.
SELECT * FROM
   (SELECT t1.keyval as key, t1.val as value1, t2.val as value2
    FROM   t_one t1, t_two t2
    WHERE  t1.keyval = t2.keyval(+)
    AND    decode(t2.val(+), 'A', 1, 'B', 2, 'C', 3, null) = t1.val
    UNION
    SELECT t2.keyval as key, t1.val as value1, t2.val as value2
    FROM   t_one t1, t_two t2
    WHERE  t1.keyval(+) = t2.keyval
    AND    decode(t2.val, 'A', 1, 'B', 2, 'C', 3, null) = t1.val(+))
If you're using 9i you might want to investigate the ANSI FULL OUTER JOIN syntax, which is much neater.
Cheers, APC

Similar Messages

  • I no longer have access to the back up email address I used when I set up my apple ID. I have since forgotten the answers to my security questions and am having a problem making changes to my account. What can I do?

    I no longer have access to the back up email address I used when I set up my apple ID. I have since forgotten the answers to my security questions and am having a problem making changes to my account. What can I do?

    You need to ask Apple to reset your security questions. To do this, click here and pick a method; if that page doesn't list one for your country or you're unable to call, fill out and submit this form.
    They wouldn't be security questions if they could be bypassed without Apple verifying your identity.
    (114957)

  • Senior moment? I can't find the Eject button on the menu bar preference

    Whether through temporary blindness or by virtue of a senior moment, I can't find where the preference to show or hide the Eject button on the menu bar is located.  I'm trying to hide it, as it had always been.
    Any help will be most appreciated.

    If you don't want it there then CMD drag it down, if you ever want it back...
    On your main hard drive, dig down into System > Library > CoreServices > Menu Extras. Inside that window, double-click on the icon called Eject.menu.

  • How do I reset my security questions with out having to select a new apple id or a new password?

    How do I reset my secrit questions with out having to select a new apple id or a new password when I'm at the itunes store.

    You will be able to reset them via:
    appleid.apple.com
    If you do not know your password contact Apple's expresslane:
    expresslane.apple.com

  • IN SUB QUERY WHICH LINE IS HAVING  ERROR

    HI,
    OTN MEMBERS.
    I HAVE ONE QUESTION THAT WHEN WRITING THE FOLLOWING QUERY.
    1) SELECT ENAME,SAL
    2) FROM EMP
    3) WHERE EMPNO = (
    4) SELECT EMPNO
    5) FROM EMP
    6) WHERE SAL >100 OR SAL <5000)
    AS THIS QUERY WILL NOT RUN B'COZ SUBQUERY GENERATES MORE
    THEN ONE RESULT AND THE MAIN QUERY IS HAVING (=) SINGLE
    ROW OPERATOR , BUT LINE WIZE WHICH LINE SHOULD I CHOOSE AS
    WRONG , B'COZ THERE IS TWO OPTIONS :-
    3) WHERE EMPNO =
    AND LINE
    6) WHERE SAL>100 OR SAL<5000
    THANKS

    It depends on what you need.
    6) WHERE SAL >100 OR SAL <5000) : this line generates more than one row, so if you need only one row you have to change it.
    If you can accept more than one row, then line 3 should be :
    3) WHERE EMPNO in (
    BTW, WHERE SAL >100 OR SAL <5000 always extracts all rows. Shouldn't be WHERE SAL >100 and SAL <5000 ?

  • Oracle 10g and parallel query question

    Hi Oracle on SAP Gurus!
    We are currently thinking of activating parallel query for certain segments (large application tables and indexes). We searched in SAPNet and SDN and have also studied the SAP Note 651060. But we did not find a complete answer to the following question which is very important for us:
    Which kinds of queries (despite from full table scan and index scan in partitioned indexes) support parallel queries and which ones do not support parallel queries?
    This is important for us to find out whether we have candidates for parallel queries or not.
    Thanx for any hint!
    Regards,
    Volker

    But why do you not propose to use parallel query in OLTP systems?
    If the queries are accessed very frequently you will just run out of cpu and io ressources. OLTP systems are (historical) typically multi user systems. You can off course use PQ for 'single user' activities, like index rebuilds, some batchjobs, but you shouldn't do for frequent user queries.
    If you have time look at this interesting Article [Suck It Dry - Tuning Parallel Execution|http://doug.burns.tripod.com/px.html]
    It is quite old, and you don't have to read all tech details, but i recommend having a look at the conclusions at the end.
    May it make sense to use partitioning of these tables in conjunction with parallel query?
    I know some guys, who do partitioning on OLTP systems, even SAP systems. But they don't use PQ then. The use partitioning to work on a smaller set of data. In your case the range scans, would need to scan only one partition, saving buffer cache and effectively speeding up execution. So you don't need PQ to scan all partitions at all, this would be a typical OLAP approach.
    Best regards
    Michael

  • Complex Query Question(s)

    I have two tables; one where I am defining questions and
    possible answers and another where you insert the answers. The
    table of questions is called 'public_survey', and SURVEY_ID is the
    primary key.
    The table of answers is called 'public_surveydata', where
    SURVEYDATA_ID is the primary key, SURVEYDATA_QUESTIONID is what
    links the primary key to public_survey and SURVEYDATA_CONTENTID is
    what is needed for output; the other columns are the answers.
    I need to:
    (a) output public_survey so it displays in a searchable
    manner;
    (b) using variables from the search I need to search
    public_surveydata and pull SURVEYDATA_CONTENTID.
    Now comes the part I cannot figure out; I search and I can
    pull up all the contentids that are related to each question; but I
    cannot figure out to only pull results that are shared over all
    returns. My query is a mess; somehow I need to either combine the
    query or run another query after the fact that only pulls common
    ids.
    How do I output only common contentid that are shared in all
    the queries?
    To see all the code and cfdumps in regards to this post go to
    this page:
    http://208.106.208.43/data/query.cfm
    To see the page in action sans cfdump and code go to this
    page:
    http://208.106.208.43/data/
    Thanks!

    Thanks Phil; I'm beginning to think I need to redesign it as
    well. Basically my reasoning for the tables was that I wanted a
    table where I could dynamically add questions that would display a
    y/n, dropdown or checkbox answer - this in turn is linked to
    another table (posts) by the contentid (see
    http://208.106.208.43/data/query.cfm
    The idea is to have a dynamic database feature that I could
    change on the fly; for example -- if another question is to be
    added to the post (i.e. Region) then I can quickly add it to all
    data using a query without having to actually touch the database.
    This is the form that creates these questions:
    http://208.106.208.43/data/survey.cfm
    However... that said - I know the easiest way to fix it would
    be to just pull these columns out and stick them in the content
    table; however that doesn't allow me to set up a dynamic table
    where I can quickly change the questions.
    How would you write a dynamic databases where you can quickly
    insert fields and link them to other tables?

  • Duplicate, Unique field value query question

    I guess this might be a straight forward question/answer but here goes:
    I have a table with two fields a1,a2. a1 is the primary key and is of number data type. a2 is varchar2(30).
    given that there might be duplication in the a2 field, I need to write a query to extract the values of a1 that go with each duplicate value in a2.
    All help is appreciated.

    WITH DATA AS(
    SELECT 1 ID,'TOM' a2,'TOM' a3 FROM dual UNION
    SELECT 2,'TOM','TOM' FROM dual UNION
    SELECT 3,'KYTE','TOM' FROM dual )
    SELECT * FROM DATA WHERE (a2,a3) IN (
    SELECT a2,a3 FROM DATA
    GROUP BY a2,a3
    HAVING COUNT(0)>1
    Cheers!!!
    Bhushan
    Edited by: Buga on Nov 25, 2009 9:56 AM
    Included example

  • Query question: presidential hobbies

    Hi all, I'm having quite some trouble solving a school asignment query.
    From the tables below I need to answer the following question:
    Give the name, party and number of hobbies of the presidents who have the biggest number of hobbies within their party.
    PRES_HOBBY =           
         (pres_name:     CHAR(20), president name
    hobby:     CHAR(20)     president hobby
    PRESIDENT = (               president
    pres_name:     CHAR(20),     president name     
    birth_yr:     NUMBER(4), president birth year
    yrs_serv:     NUMBER(2), years of service               de¬ath_age:     NUMBER(2), age of death
         party:          CHAR(10),     president party     
         state_born:     CHAR(15)     state in which president born
    Now I have come up with these 2 queries who both seem to answer a part of the solution:
    This one gives the president who has the most hobbies of ALL presidents:
    Select p.pres_name, p.party, count(h.hobby)
    From president p, pres_hobby h
    Where p.pres_name=h.pres_name
    group by p.pres_name, p.party
    having count(h.hobby) =(select max(count(h.hobby))
    from Pres_hobby h
    group by pres_name, party);
    And this one gives the number of hobbies per president:
    select p.pres_name, p.party, count(h.hobby)
    from Pres_hobby h, president p
    where p.pres_name=h.pres_name
    Group by p.pres_name, p.party;
    So I know how to get the number of hobbies per president, but how do I get SQL Plus to give me the highest number of hobbies one president has per party?
    Any pointers, suggestions or solutions are welcome :)

    well, if you want count(something) with some more
    columns, you need to have a GROUP BY clause.
    Added the Group by clause and no more error messages. Should have seen that myself. This results in the following query:
    Select p.pres_name, p.party, count(h.hobby)
    From president p, pres_hobby h
    Where p.pres_name=h.pres_name
    group by p.pres_name, p.party
    Having count(h.hobby) IN (SELECT  MAX(cnt) max_cnt                       
                              FROM (SELECT p.pres_name, p.party, count(*) cnt                            
                                    FROM president p, pres_hobby h                            
                                    WHERE p.pres_name = h.pres_name
                                    group by p.pres_name, p.party)); Problem is it doesn't return the right answer, it just gives back Teddy Roosevelt with 7 hobbies, which is the same answer I got from my starting query at the beginning of the thread.
    even then your query is wrong. how can you just
    compare the joined records with numbers?I don't understand what you mean here, to me, it seems I'm comparing count(h.hobby) to a MAX(count), so I would be comparing a number with a number.

  • Simple Query Question - How do I return the Last 3 records of a Table?

    Question.
    For example, I have a table that has 50 records.
    How do I, specify in SQL to only return the last 3 records of the table.
    Select a.* from table a where ????

    I was just trying to show an example to a friend on
    how something like this would work and if it was even possible. But it won't work. Here's a simple example:
    SQL> create table emp
      2  (id)
      3  as
      4  select object_id
      5  from   all_objects
      6  order  by object_id;
    Table created.
    SQL> select *
      2  from  (select rownum rn
      3               ,b.*
      4         from   emp b)
      5  where  rn > ( select (max(rownum) - 3)
      6                from    emp)
      7  ;
            RN         ID
         40830      55891
         40831      55892
         40832      55893So far, so good. These are the "last 3" rows inserted. Now delete a bunch of rows and insert 3 new ones:
    SQL> delete emp where id < 40000;
    33423 rows deleted.
    SQL> commit;
    Commit complete.
    SQL> insert into emp values (60000);
    1 row created.
    SQL> insert into emp values (60001);
    1 row created.
    SQL> insert into emp values (60002);
    1 row created.
    SQL> commit;
    Commit complete.
    SQL> select *
      2  from  (select rownum rn
      3               ,b.*
      4         from   emp b)
      5  where  rn > ( select (max(rownum) - 3)
      6                from    emp)
      7  ;
            RN         ID
          7410      55891
          7411      55892
          7412      55893Here's the problem. Even though the "last 3 rows" are 60000 - 60002, I still get the same ones as the first query.

  • General JPA query question

    Hello world,
    I'm new to JPA 2.0 and there are few things I don't understand.
    BTW: I can't figure out the keywords to search for this question, so please pardon me if it's one of the most asked.
    Using the Preview, I've seen that alignment went straight to Hell, so I tried to make this as readable as I could using pipes in place of white spaces in the result sets.
    I have a couple of tables:
    CUST table (for customers):
    CUST_ID (pk, integer)
    CUST_NAME (varchar)
    ORD table (for orders):
    ORD_ID (pk, integer)
    ORD_STATUS (char) can be: N for new, S for shipped, D for delivered
    CUST_ID (fk, integer)
    The relationship is, of course, a "one to many" (every customer can place many orders).
    Content of the tables:
    CUST_ID|CUST_NAME
    1|elcaro
    2|tfosorcim
    3|elppa
    ORD_ID|ORD_STATUS|CUST_ID
    2|N|1
    3|N|1
    4|N|1
    5|S|1
    6|S|1
    7|D|1
    8|D|1
    9|D|1
    10|D|2
    11|N|2
    12|S|3
    13|S|3
    Here's how I annotated my classes:
    Customer.java:
    @Entity(name = "Customer")
    @Table(name = "CUST")
    public class Customer implements Serializable
    private static final long serialVersionUID = 1L;
    @Id
    @Column(name = "CUST_ID")
    private Integer id;
    @Column(name = "CUST_NAME")
    private String name;
    @OneToMany(mappedBy = "customer")
    private List<Order> orders;
    // Default constructor, getters and setters (no annotations on these)
    Order.java:
    @Entity(name = "Order")
    @Table(name = "ORD")
    public class Order implements Serializable
    private static final long serialVersionUID = 1L;
    @Id
    @Column(name = "ORD_ID")
    private Integer id;
    @Column(name = "ORD_STATUS")
    private Character status;
    @ManyToOne
    @JoinColumns
    @JoinColumn(name = "CUST_ID", referencedColumnName = "CUST_ID")
    private Customer customer;
    // Default constructor, getters and setters (no annotations on these)
    Everything works just fine, the following JPQL query yields the results I expected:
    select c from Customer c
    it returns three objects of type Customer, each of which contains the orders that belong to that customer.
    But now, I want to extract the list of customers that have orders in status 'N', along with the associated orders (only the status 'N' orders, of course).
    Back in the good ol' days I would have written an SQL query like this:
    select c.cust_id, c.cust_name, o.ord_id, o.ord_status
    from cust c
    inner join ord o on (o.cust_id = c.cust_id)
    where o.ord_status = 'N'
    and it would have returned the following result set:
    CUST_ID|CUST_NAME|ORD_ID|ORD_STATUS
    1|elcaro|2|N
    1|elcaro|3|N
    1|elcaro|4|N
    2|tfosorcim|11|N
    The following JPQL query, however, doesn't yield the expected results:
    select distinct c from Customer c join c.orders o where o.status = 'N'
    it returns the correct set of customers (customer 'elppa' doesn't have any status 'N' order and is correctly excluded), but each customer contains the full set of orders, regardless of the status.
    It seems that the 'where' clause is only evaluated to determine which set of customers has to be extracted and then the persistence provider starts to navigate the relationship to extract the full set of orders.
    Thinking a little about it, I must admit that it makes sense.
    I then tried out another JPQL query:
    select c, o from Customer c join c.orders o where o.status = 'N'
    this JPA query yields results that are similar to the ones produced by the previous SQL query: each result (4 results as expected) is a 2-object array, the first object is of type Customer and the second object is of type Order. But, again, the objects of type Customer contain the full set of related orders (as I expected, this time). Not to mention the fact that now the orders are not contained in the Customer objects, but are returned separately, just as in an SQL result set.
    Now the question is:
    Is it possible to write a JPA query that filters out, not only the customers that don't have an order in status 'N', but the related orders (fetched during relationship navigation) that are not in status 'N' as well?
    What I'd like to be able to get is a 2-customer result where each customer contains only its status 'N' orders.
    I read the Java EE 6 Tutorial and one of the examples (the Order Application) has a schema that is similar to mine, but I couldn't find a query like this (in the downloaded source code).
    Although I think the above is standard behavior, I use an Oracle Weblogic 12c server (through its Eclipse adapter) and the persistence provider appears to be EclipseLink.
    Thanks in advance.
    Best regards,
    Stefano
    Edited by: user11265230 on 17-apr-2012 14.11

    Hello,
    When returning an entity from JPQL, it gives you the entity as it is in the database. Your "select distinct c from Customer c join c.orders o where o.status = 'N'" is asking for all customers that have an order with a status of 'N', so that is what it gives you. There is no condition to filter anything on the relationship when building the Customer object in JPA - doing so would mean returning a managed entity that does not reflect what is in the database. This would affect other queries, since JPA requires that queries return the same instance of an entity regardless of the query that is used to bring it back. So a query using your "where o.status = 'N'" would cause conflicting results when used with a query using "where o.status = 'Y'". And these queries would make the EntityManager unable to determine what has changed on the returned objects.
    EclipseLink does have the ability to filter over relationships, it is just not available through standard JPA and I would strongly discourage it. Instead of querying for Customers, why not change the query to get Orders instead -
    "select o from Customer c join c.orders o where o.status = 'N'". Assuming Orders have a ManyToOne back reference to their Customer, this will mean you do not need to travers the Customer-> order relationship. If using
    "select c, o from Customer c join c.orders o where o.status = 'N'"
    I am not sure why you would use the orders from the returned customers instead of the orders returned in the results though.
    You could also return "select c.id, c.name, o.id, o.status from Customer c join c.orders o where o.status = 'N'" which is the equivalent of what you would get from the SQL you initially posted.
    Regards,
    Chris

  • Left Join Query Question

    Version 10.2.0.4.0
    I have a question on the expected behavior of the query below.
    When I run the query below with the constraint on t1.partid = 789,  I get the query result t2.Indicator showing "SPECIAL" as expected.
    However, if I remove the constraint, and return all orders and parts, for the "789" part, the Indicator column is null.
    select t1.orderid, t1.partid, t2.Indicator
    from Orders a left outer join
    select partid, 'SPECIAL' as Indicator
    from vendors
    where vendorname like '%ABC%'
    ) t2
    on t1.partid = t2.partid
    where t1.partid = '789'
    I can address the issue with a case statement (below) or likely restructuring into a better statement. 
    But I'm just curious if this is expected or if there is some SQL rule being violated in the first example.
    I tried to search for this to see if it was already addressed but didn't have much luck.
    This works:
    select t1.orderid, t1.partid,
    case when t1.partid is not null then "SPECIAL" else null end as Indicator
    from Orders a left outer join
    select partid, 'SPECIAL' as Indicator
    from vendors
    where vendorname like '%ABC%'
    ) t2
    on t1.partid = t2.partid

    Sorry, it's been a while since I posted and should have read the rules.  And I didn't properly reference the alias.  So Post #1 was bad. 
    When I mockup a small set of data (shown below), I don't get the error.  The original query actually joins to a few other (seemingly) irrelevant tables and I tried to simplify it here  So I guess if I can't replicate it, then there might not be much assistance that can be provided.
    This was more of a curiousity than anything else to see if perhaps someone came across this before.
    For what it's worth:
    create table t1 (orderid number,
                 partid varchar2(20)
    create table t2
            (vendorid varchar2(20),
             partid varchar2(20)
    insert into t1 values(1, '123');
    insert into t1 values(2, '456');
    insert into t1 values(3, '789');
    insert into t2 values ('ABC','789');
    insert into t2 values ('DEF','123');
    insert into t2 values ('EFG','456');
    insert into t2 values ('ABC','7891');
    insert into t2 values ('DEF','1231');
    insert into t2 values ('EFG','4561');
    select t1.orderid, t1.partid, t2.Indicator
    from t1 left outer join
    select partid, 'SPECIAL' as Indicator
    from t2
    where vendorid like '%ABC%'
    ) t2
    on t1.partid = t2.partid
    the query that gives unexpected behavior is (although I can't replicate on this simplified version):
    select t1.orderid, t1.partid, t2.Indicator
    from t1 left outer join
    select partid, 'SPECIAL' as Indicator
    from t2
    where vendorid like '%ABC%'
    ) t2
    on t1.partid = t2.partid

  • 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.

  • Urgent , Two Query questions ...

    Hello everybody ,
          i have created a query in our production system . but i found some people can change my query setting (ex : my local fileds & selection fields ) , has any one can tell me how can i disable the 'Change' function in 'SQ01' ? many thanks !
    (i also use 'su24' to check the authorzation object in 'SQ01' , but i don't know which one can help me to solved this case)
          another question that is when i execute the query i found one of the field's sequence was wrong . but this query is used everyday & nobody has changed it . but when i use  sort this function to make it & it seems ok . therefore i think the problem is in the table index , right ? Has anyone can tell me how to check it ?
    Best Regards,
    Carlos

    hi Ramki
         the query is made by ourselves . the data is only fetched from the billing table (vbrk & vbak) . but today i found some filed's sequence was wrong & i don't know what cause this .
    another problem is that could you tell me how to disable 'Change' function in 'SQ01' ?
    many thanks ~
    Best Regards,
    Carlos

  • Named query question

    Hi Guys,
    I have the following problem - I know I did something wrong, but I cannot figure out how to correct it. Here is my question:
    I have a table tableA, with composite key (col1, col2, col3, col4). I mapped the table, and create a Toplink named query (findCol3List)as such:
    select distinct col3
    from tableA
    where col1=#col1 and col2=#col2
    I created an EJB session method getCol3List(col1, col2) -
    now when I run the application to call this EJB method, I got the following error at line:
    List results = (List)session.executeQuery("findCol3List", String.class, params);
    Exception Description: Missing descriptor for [java.lang.String] for query named [findCol3List].
    I know there are multiple mistakes in my approach, but with my limited Toklink knowledge, I could not figure out.
    Any help with be appreciated!

    hello,
    The executeQuery method is trying to look up the "findCol3List" in the descriptor for the class passed in. It is complaining because you passed in String.class which does not have a valid descriptor.
    How/where did you define the named query? Chances are you defined it in the class used for TableA, and so should specify it in the executeQuery method:
    session.executeQuery("findCol3List", tableA.class, params);
    Best Regards,
    Chris

Maybe you are looking for