Joining Tables Involving "one to many"

I have a situation where a customer gets a basic "license" to perform a business then he or she may get multiple "permits" to perform sub tasks of the basic business plan.
I must join the "license" table with the "permits" table. I have currently joined them with a license identification number that appears in both tables, without qualification as to "one to one" or "outer join".
There is always a license ID number in the licensing table.
There may be multiple occurrance's of the license ID number in the permits table.
Should I qualify the join?

Thank you for the rapid response. I am returning to the Discoverer product after a long absence and need brushing up on many standard concepts.
In a recent response to a question on joins by another requestor, the forum respondent advised that "you didn't include the join in a condition i.e. master table item x is equal to detail table item x". Isn't it a redundancy to put the join in a condition if a joins already exists for the detail table information. I know that I can trick the CBO into more rapid response by including redundant conditions in the query such as a date range that includes all the records in a table. A test demonstrated that the inclusion of the join in the condition caused the data to literally explode on the screen.

Similar Messages

  • JOIN TABLES IN ONE REPORT

    Hi,
    I'm trying to join some tables in one report. I was successful with it, until I added one table which has many records for one primary key in the main table. I used Order by and Limit to select only the latest row, but then I got this error: Query cannot be parsed, please check the syntax of your query. (ORA-00907: missing right parenthesis)
    The sql is here:
    select
    t.TICKET_ID "Ticket Id",
    t.RECEIVED_DATE "Received Date",
    t.QUOTE_NUMBER "Quote Number",
    r.REQUEST_NAME "Request Type",
    s.STATUS_NAME "Status",
    p.PRIORITY_NAME "Priority",
    t.NUMBER_OF_SUBLINES "Number Of Sublines",
    t.QUOTE_VALUE "Quote Value",
    c.CURRENCY_NAME "Currency",
    t.QUOTE_START_DATE "Quote Start Date",
    t.CUSTOMER_NAME "Customer Name",
    t.REQUESTER_EMAIL "Requester",
    st.STRIPE_NAME "Stripe",
    tm.TEAM_NAME "Team",
    a.ANALYST_NAME "Quote Analyst",
    (select g.GATE_COMM from QTMT_GATE_COMM g where g.TICKET_ID=t.TICKET_ID order by g.GATE_COMM_ID desc limit 1)GATE_COMM,
    ac.ANALYST_COMM "Quote Analyst Comment",
    cc.CLOSE_COMM "Closing Comment",
    se.SERVICE_NAME "Type Of Service",
    ro.REOPEN_NAME "Reopen",
    t.ASSIGNED_DATE "Assigned Date",
    t.LAST_UPDATED "Last Updated",
    t.DATE_COMPLETED "Date Completed",
    t.EFFORT "Effort"
    from
    QTMT_TICKETS t,
    QTMT_REQUEST_TYPE r,
    QTMT_STATUS s,
    QTMT_PRIORITY p,
    QTMT_CURRENCY c,
    QTMT_STRIPE st,
    QTMT_TEAM tm,
    QTMT_ANALYST a,
    QTMT_ANALYST_COMM ac,
    QTMT_CLOSE_COMM cc,
    QTMT_SERVICE se,
    QTMT_REOPEN ro
    where
    t.REQUEST_TYPE_ID=r.REQUEST_TYPE_ID and
    t.STATUS_ID=s.STATUS_ID and
    t.PRIORITY_ID=p.PRIORITY_ID and
    t.CURRENCY_ID=c.CURRENCY_ID and
    t.STRIPE_ID=st.STRIPE_ID and
    t.TEAM_ID=tm.TEAM_ID and
    t.ANALYST_ID=a.ANALYST_ID and
    t.ANALYST_COMM_ID=ac.ANALYST_COMM_ID and
    t.CLOSE_COMM_ID=cc.CLOSE_COMM_ID and
    t.SERVICE_ID=se.SERVICE_ID and
    t.REOPEN_ID=ro.REOPEN_ID
    Could you please let me know what do I have wrong?
    Thank you and best regards,
    Vladimir

    It's a problem with me not being able to run the code to test it. Basically the problem is that the subquery is nested too deeply to be able to see the QTMT_TICKETS table. It is not 'missing' as ApexBine suggests but it is unavailable. The most deeply nested subqueries execute first, and that one is executing before the QTMT_TICKETS table is available to it. Off the top of my head, the easiest thing then would be to create a function to get the GATE_COMM value (I'm guessing at the data types):
    FUNCTION gate_comm (p_ticket   NUMBER)
    RETURN VARCHAR2
    AS
      CURSOR c_gc IS
        SELECT g.GATE_COMM
        FROM   QTMT_GATE_COMM g
        WHERE  g.TICKET_ID = p_ticket
        ORDER BY g.GATE_COMM_ID DESC;
    BEGIN
      FOR v_Lp IN c_gc LOOP
        RETURN v_Lp.gate_comm;
      END LOOP;
    END;Then you can replace the failing subquery in the SQL with gate_comm(t.TICKET_ID)

  • How to resolve many-to-many join by 2 one-to-many joins

    Hi,
       I was asked many times how to resolve many to many relationship between two tables. I read to use 2 one -to- many relationships to resolve this. Can some expalin me when many to many relationship occurs between two tables and how to reslove them with practicle examples. Is there any article on this?
    Regards,
    Nanda Kishore

    Hi,
    Please check below link.
    http://www.forumtopics.com/busobj/viewtopic.php?p=859029&sid=20d79e3df07b0d8b41aadfbd902bb6b2
    http://blog.oaktonsoftware.com/2011/04/bridge-tables-and-many-to-many.html
    Thanks,
    Amit

  • How merge query results from joined table into one additional column

    <code>
    Here is example
    TABLE A:
    id | value
    1 | a
    2 | a
    3 | b
    TABLE B
    id | id_in_table_a | value
    1 | 1 | d
    2 | 1 | e
    3 | 2 | g
    </code>
    this select should get all columns from table A where value = 'a' and all values related to this record from B merged to one column separated for example with pipe, so the output should looks like this
    <code>
    id | value | merged_column
    1 | a | d|e
    2 | a | g
    </code>
    thanks for help

    If you are on 10g, you can use this:
    SQL> create table a
      2  as
      3  select 1 id, 'a' value from dual union all
      4  select 2, 'a' from dual union all
      5  select 3, 'b' from dual
      6  /
    Tabel is aangemaakt.
    SQL> create table b
      2  as
      3  select 1 id, 1 id_in_table_a, 'd' value from dual union all
      4  select 2, 1, 'e' from dual union all
      5  select 3, 2, 'g' from dual
      6  /
    Tabel is aangemaakt.
    SQL> select id
      2       , value
      3       , rtrim(v,'|') merged_column
      4    from ( select id
      5                , value
      6                , v
      7                , rn
      8             from a
      9                , b
    10            where a.id = b.id_in_table_a
    11            model
    12                  partition by (a.id)
    13                  dimension by (row_number() over (partition by a.id order by b.id) rn)
    14                  measures (a.value, cast(b.value as varchar2(20)) v)
    15                  rules
    16                  ( v[any] order by rn desc = v[cv()] || '|' || v[cv()+1]
    17                  )
    18         )
    19   where rn = 1
    20  /
       ID VALUE MERGED_COLUMN
        1 a     d|e
        2 a     g
    2 rijen zijn geselecteerd.Regards,
    Rob.

  • How to link a fact table to one dimension many times

    I have fact table which contains four date fields and I want to connect all of them to the Time dimension. I think I probably must split this fact table to multiple tables and then link them to dimensions. What is the right way to solve this kind of problem?
    Example: Fact table: TimeIn, TimOut, TimeStart, TimeStop, InPlace, OutPlace, StartPlace, StopPlace, Speed, Weight, Width, Height .....
    Thank you

    Hello Kostis,
    thank you for your answer. I don't fully understand you. Can you show me short example, please? I create alias table for time dimension on Physical Layer - original table is TimeDayDim and I create aliases TimeDayDim1, TimeDayDim2, TimeDayDim3, TimeDayDim4. Then I create foreign key Fact.Time1 -> TimeDayDim1, Fact.Time2 -> TimeDayDim2, Fact.Time3 -> TimeDayDim3, Fact.Time4 -> TimeDayDim4. And what now? Must I create these table api Bussines Model and create new time dimensions at bussiness model????
    I need in Answers ONE Time dimension. I think I must split my fact table to four tables ... (time1, place1 ...) (time2, place2 ...) (time3 place3...) (time4 place4...) then link those tables to Time dimension (but I dont know where I can split those tables - on Physical Layer or on Bussines Layer).
    I suppose that I will have in Answers one time dimension and four facts tables and I will be able to query them. (for example: Time.Days, Fact1.Place1, Fact3.Speed, Fact4.Count Criteria: Time.Year = 2008)
    Best Regards Vlada

  • Workbench-Cannot Give Joining to One-To-Many

    Hi there,
    i am using toplink workbech 10g release 2(10.1.3.0DP4) build 050715. In workbench, i want to put "use joining" to a one-to-many relationship. Joining can be applied to one-to-many relationships from the java code but in workbench i cannot give joining to the one-to-many relationships. There is no checkbox for that property. I can only check batch reading. Is it true, or is there a problem with my mapping workbench?

    This is true, there is currently no 1-m joining support in the Mapping Workbench, nor can you set this at the mapping level in the code API. 1-m joining can only currently be set at the query level in the code API. Note that in general batch reading for 1-m is more performant than joining, so you may want to consider using it instead.

  • One to many table insert in JDBC

    hi all, I have an online form when it submit the value will get into three table, one child table is one to many relation to parent , like
    parent  table have(     UserId        int Not null,     UniversityN      varchar(10) Not null,   ...   PRIMARY KEY  (UserId)   PaymentId          int Not null  auto_increment ,     UserId        int Not null, ) child Table( PaymentId          int Not null  auto_increment , UserId        int Not null, UniversityN      varchar(10) Not null, record1            varchar(50) Not null, record2            varchar(50) Not null, record13          varchar(50) Not null,     PRIMARY KEY  (PaymentId),     FOREIGN Key(UserId) REFERENCES Parent(UserId) on Delete     Cascade on update cascade)Type=InnoDB DEFAULT CHARSET=utf8; )
    then I have
    conn.setAutoCommit(false); calstat1 = (CallableStatement) conn.prepareCall(                     "{ call Insert_Parent(?,?,?,?,?,?,?,?,?,?,?,? )}"); calstat2 = (CallableStatement) conn.prepareCall(                     "{ call Insert_ChildRecords(?,?,?,?,?,?,?,?,?,?,?,? )}");
    and the UniversityN , recored1, record2, record3 all come from the input form, how can i handle this one to many insert? for each submit the parent table always one row, and the child table is a lease one up to five rows the if the did have five the userId , and UniversityN is same, but the recore 1. record2... is different
    thank you

    I think you have a problem with your database table definitions that you need to fix before coding java.
    In the above, I dont think you need the first PaymentId (in the 'have' table). I also dont think your tables are normalized since I see 'UniversityN' in both the parent and child record. Also, you should rename your tables to something meaningfull rather than 'have' and 'table'. Also, rename the fields better. Ideally get your friendly neighborhood DBA to review your tables. Only when they are well defined should you start to work on java.
    Here's an example:
    parent  table:
    Customer(
        id                number, not null, primary key, must be unique, auto increment
        userId         number, not null, natural key, must be unique
        universityN  varchar(10), Not null
    child Table:
    Payment(
        id                      number, not null, primary key, must be unique, auto increment
       customer_id        number, not null, foreign key to the customer table's id field
       record1               varchar(50), not null,
       record2               varchar(50), not null,
       record3               varchar(50), not null,
        Cascade on delete record when parent is deleted
        dont cascase update record
    )Note: in the above, record1,record2, record3 should probably be put in its own table, with a foreign key back to the payment table.
    Note: each table in your database has its own id that is auto generated. Some have a natural key (like userID) that can be used to look up records independent of the auto generated key.
    Note the customer_id (foreign key) has the name of table it refers to (customer) and the key its refering to in that table (id).
    Note: when you insert a new customer, you need to get the newly generated id. Use the natural key to retreive the id in order to put it in the new payment table's customer_id field.
    I suggest you dont cascade delete any child table. Do it programmatically so you can better learn the issues that come up as you insert, update, and delete various parent and child combinations.

  • One to Many table join -- concat field per record grouped by id

    Post Author: wm5
    CA Forum: Formula
    Hello,
    I am using Crystal Reports XI and have two tables that have a one to many relationship and are joined by an JobID (number).
    Below is a sample with relative fields for each table.
    job_table: JobID (number), Manager (text), Status (text)
    jobaudit_table : JobAuditID (number), JobID (Number), FormID (Number)
    There is a one to many relationship with jobaudit_table having multiple records for each JobID in job_table.
    I have created a Group Header using the job_table.JobID and suppressed the detail section.
    In the group header for each JobID I display the JobID, Manager, Status. I also use the below formula to determine if any records in the jobaudit_table has a record where FormID = 90. If so, I display "Yes". If not, "No".
    So my report currently looks like.
    JobID     Manager     Status     Audit Performed
    1           Manager 1  Closed           N
    2          Manager 2   Closed           Y
    Here are the formula's I use to determine if any records in jobaudit_table contains a record where FormID = 90.
    @ja90exists
    if {jobaudit_table.FormID} = 90 then    1else    0;
    if sum({@ja90exists},{job_table.JobID}) = 0 then    "No"else    "Yes";
    Everything so far works fine. What I would like to do now is add a hyperlink to a script to view the job audit when in the above report the "Audit Performed" column is "Yes"
    So Report is now:
    JobID     Manager     Status     Audit Performed
    1           Manager 1  Closed           N
    2          Manager 2   Closed           Y (hyperlink to view audit)
    I cannot figure out how to gather the valid JobAuditIDs where FormID = 90 grouped by JobID to be used in the Group Heading section of the report.
    Also, it is unlikely, but possible that more than one job_audit record exists with FormID = 90 per JobID. So, my hyperlink could look like http://mysite.com/viewjobaudit.aspx?jobid=[jobaudit_table.JobAuditID],[jobaudit_table.JobAuditID] .
    Thanks for any help. And if this post is not clear let me know and I will clarify.
    wm5

    Post Author: bettername
    CA Forum: Formula
    Although I can't think of a way to get multiple hyperlinks, this should be a start.  It (should) hyperlink to the last job/audit in the group that formID of 90.  Oh, I assumed that the hyperlink should have been  xxxx...jobID,jobAuditID! 
    I think there may be a way of getting hyperlinks to every "90" record, but that will involve a subreport, so lets try this first...
    1 - everything from your group header to the group footer...
    2 -  add a formula into the group header that says:
    whileprintingrecords;
    stringvar jobauditID="";
    stringvar jobID:=";
    3 - Then add a formula to the details section:
    whileprintingrecords;
    stringvar jobauditID;
    stringvar jobID;
    if {jobaudit_table.FormID} = 90
    then (jobID:=totext({job_table.job_id},0,""); jobauditID:=totext({jobaudit_table.jobaudit_id},0,"")
    4 - Finally, on your "Audit Performed" formula, have a conditional hyperlink that says:
    whileprintingrecords;
    stringvar jobauditID;
    stringvar jobID;
    if {@audit performed} = "Y" then http://mysite.com/viewjobaudit.aspx?jobid=jobID","+jobauditID

  • Unidirectional one-to-many with join table

    According to http://docs.jboss.org/hibernate/orm/3.5/reference/en-US/html/associations.html#assoc-unidirectional-12m "A unidirectional one-to-many association on a foreign key is an unusual case, and is not recommended", instead they recommend using a join table, e.g.
    create table Person ( personId bigint not null primary key )
    create table PersonAddress ( personId not null, addressId bigint not null primary key )
    create table Address ( addressId bigint not null primary key )
    However if doing this, when using SQLDeveloper the Address table does not appear as a child table of Person, which it should be as a unidirectional one-to-many meaning that I can't create a cache group for Person and subsequently Person.
    Is this something that can be worked around as I'm using a legacy schema created from Hibernate/JPA and the implications of changing are quite substantial?
    Thanks

    Hi Gennady,
    Apologies but my question was not clear enough. The schema structure that I have inherited is as follows:
    CREATE TABLE T_PERSON ( PERSONID NUMBER PRIMARY KEY, PERSONFIRSTNAME VARCHAR2(20), PERSONLASTNAME VARCHAR2(20) );
    CREATE TABLE T_PERSONADDRESS (PERSONID NUMBER NOT NULL, ADDRESSID NUMBER NOT NULL PRIMARY KEY );
    CREATE TABLE T_ADDRESS ( ADDRESSID NUMBER  PRIMARY KEY, ADDRESSTEXT VARCHAR2(200) );
    ALTER TABLE T_PERSONADDRESS ADD CONSTRAINT FK_PERSON_ADDR_PERSON_ID FOREIGN KEY (PERSONID) REFERENCES T_PERSON(PERSONID);
    ALTER TABLE T_PERSONADDRESS ADD CONSTRAINT FK_PERSON_ADDR_ADDR_ID FOREIGN KEY (ADDRESSID) REFERENCES T_ADDRESS(ADDRESSID);This is implementing a unidirectional one-to-many relationship between T_PERSON and T_ADDRESS according to the Hibernate and JPA recommendation. As far as I can see most schema designers would do this using by adding a column "PERSON_ID" (and associated FK) on the T_ADDRESS table and therefore not needing the T_PERSONADDRESS table.
    This being what it is, I would then like to create a cache-group as follows:
    CREATE READONLY CACHE GROUP "CACHEGROUPADDRESSES"
    AUTOREFRESH MODE INCREMENTAL INTERVAL 5 MINUTES
    STATE PAUSED
    FROM
      "SCHEMA1"."T_PERSON" (
        "PERSONID"        NUMBER            NOT NULL,
        "PERSONFIRSTNAME" VARCHAR2(20 BYTE),
        "PERSONLASTNAME"  VARCHAR2(20 BYTE),
        PRIMARY KEY("PERSONID")
      "SCHEMA1"."T_ADDRESS" (
        "ADDRESSID" NUMBER NOT NULL,
        "ADDRESSTEXT" VARCHAR2(20 BYTE),
        PRIMARY KEY("ADDRESSID")
      "SCHEMA1"."T_PERSONADDRESS" (
        "PERSONID"  NUMBER NOT NULL,
        "ADDRESSID" NUMBER NOT NULL,
        PRIMARY KEY("ADDRESSID"),
        FOREIGN KEY("PERSONID")
          REFERENCES "SCHEMA1"."T_PERSON"("PERSONID"),
        FOREIGN KEY("ADDRESSID")
          REFERENCES "SCHEMA1"."T_ADDRESS"("ADDRESSID")
      )This however gives me the error "TT8222: Multiple parent tables found" because TimesTen has failed to identify the one-to-many-using-link-table pattern.
    Without a schema re-write is there anything that I can do, alternatively will this be looked at for a future release of TimesTen?
    Edited by: TrisStev on Apr 16, 2012 10:37 AM

  • One-to-Many implemented with a join Table

    Hello,
    Is it possible to implement a One-to-Many relationship with a join table, just like
    the Reference Implementation does.
    Regards,
    Jeroen

    "Jeroen Ferdinandus" <[email protected]> wrote in
    news:[email protected]:
    Is it possible to implement a One-to-Many relationship with a join
    table, just like the Reference Implementation does.Not with our CMP, you will have to resort to BMP for that.
    Cedric

  • Unidirectional one-to-many relationship without a join table

    Hello,
    I have 2 classes, Invoice and InvoiceLine, and a one-to-many unidirectional relationship from Invoice to InvoiceLine. By default, with JPA, it would be mapped by a join table with foreign keys that refer to the 2 tables which represent Invoice and InvoiceLine.
    My problem: the database has already a foreign key in the table which represents InvoiceLine that refers to the table which represents Invoice.
    To solve my problem I could make the relationship bidirectional but I would like to know if it is possible to keep it unidirectional and to use the foreign key which already exists (in the table that represents InvoiceLine). How could I declare the mapping with JPA?
    Thanks in avance for your answers.

    JPA requires that any @OneToMany mapping not using a join table have an inverse @ManyToOne mapping. In general the foreign key in the target object needs to be mapped and a @ManyToOne mapping is normally the best way to map it, so making the relationship bi-directional is your best option.
    There are other ways in TopLink to map a unidirectional 1-m, but these are not directly supported by the JPA spec. You could define a TopLink OneToManyMapping for the relationship through a TopLink DescriptorCustomizer and the code API. You would still need to map the foreign key in the target object some way, but you could use a @Basic mapping for this as long as you keep it in synch.
    In TopLink you could also map the relationship using an AggregateCollectionMapping (basically a collection of embeddables), and then not require mapping the foreign key in the target, but this imposes limitations on the target object (must be treated like an embeddable instead of entity). You would also need to configure the target object to be an aggregateCollectionDescriptor if using this option.

  • One-to-many table linking

    Hi all,
    I'm trying to write a report with multiple one-to-many table links.  The issue is I only want a single record from the linked tables.  The main table is an item table and the linked tables are issue and receipt.  I want to display information from the last issue record and the last receipt record along with the item information.  Not sure how to restrict the joins to just a single record (also need to sort desc on dates in the linked tables).  Does this require the use of a view? or a custom sp?
    Thanks for taking your time to help.
    Kevin

    To bring back a single record then you will probably need to use a View , command or SP.
    However, in Crystal you can bring back multiple records and only display the record you want. The easiest way will be to group
    Data on Date and then Item code.
    Place the data you want to see in in Item group footer and suppress details and all other Group headers and footers.
    To get receipt date just use a maximum summary of receipt date in item group footer
    Ian

  • How just return one row of a one to many join..

    So I have a one to many join where the SMOPERATOR table has data I need however it has a couple of rows that match the JOIN condition in there. I just need to return one row. I think this can be accomplished with a subquery in the join however have not been able to come up with the right syntax to do so.
    So:
    SELECT "NUMBER" as danumber,
    NAME,
    SMINCREQ.ASSIGNMENT,
    SMOPERATOR.PRIMARY_ASSIGNMENT_GROUP,
    SMOPERATOR.WDMANAGERNAME,
    SMINCREQ.owner_manager_name,
    SMINCREQ.subcategory, TO_DATE('01-'||TO_CHAR(open_time,'MM-YYYY'),'DD-MM-YYYY')MONTHSORT,
    (CASE WHEN bc_request='f' THEN 'IAIO'
    WHEN (bc_request='t' and substr(assignment,1,3)<>'MTS') THEN 'RARO'
    WHEN (bc_request='t' and substr(assignment,1,3)='MTS') THEN 'M'
    ELSE 'U' end) as type
    from SMINCREQ
    left outer join SMOPERATOR on SMINCREQ.assignment=SMOPERATOR.primary_assignment_group
    WHERE SMINCREQ.owner_manager_name=:P170_SELECTION and SMOPERATOR.wdmanagername=:P170_SELECTION
    AND open_time BETWEEN to_date(:P170_SDATEB,'DD-MON-YYYY') AND to_date(:P170_EDATEB,'DD-MON-YYYY')
    AND
    (bc_request='f' and subcategory='ACTIVATION' and related_record<>'t')
    OR
    (bc_request='f' and subcategory<>'ACTIVATION')
    OR
    (bc_request='t' and substr(assignment,1,3)<>'MTS')
    order by OPEN_TIMe

    Hi,
    This sounds like a Top-N Query , where you pick N items (N=1 in this case) off the top of an orderded list. I think you want a separate ordered list for each assignment; the analytic ROW_NUMBER function does that easily.
    Since you didn't post CREATE TABLE and INSERT statements for your sample data, I'll use tables from the scott schema to show how this is done.
    Say you have a query like this:
    SELECT       d.dname
    ,       e.empno, e.ename, e.job, e.sal
    FROM       scott.dept  d
    JOIN       scott.emp   e  ON   d.deptno = e.deptno
    ORDER BY  dname
    ;which produces this output:
    DNAME               EMPNO ENAME      JOB              SAL
    ACCOUNTING           7934 MILLER     CLERK           1300
    ACCOUNTING           7839 KING       PRESIDENT       5000
    ACCOUNTING           7782 CLARK      MANAGER         2450
    RESEARCH             7876 ADAMS      CLERK           1100
    RESEARCH             7902 FORD       ANALYST         3000
    RESEARCH             7566 JONES      MANAGER         2975
    RESEARCH             7369 SMITH      CLERK            800
    RESEARCH             7788 SCOTT      ANALYST         3000
    SALES                7521 WARD       SALESMAN        1250
    SALES                7844 TURNER     SALESMAN        1500
    SALES                7499 ALLEN      SALESMAN        1600
    SALES                7900 JAMES      CLERK            950
    SALES                7698 BLAKE      MANAGER         2850
    SALES                7654 MARTIN     SALESMAN        1250Now say you want to change the query so that it only returns one row per department, like this:
    DNAME               EMPNO ENAME      JOB              SAL
    ACCOUNTING           7782 CLARK      MANAGER         2450
    RESEARCH             7876 ADAMS      CLERK           1100
    SALES                7499 ALLEN      SALESMAN        1600where the empno, ename, job and sal columns on each row of output are all taken from the same row of scott.emp, though it doesn't really matter which row that is.
    One way to do it is to use the analytic ROW_NUMBER function to assign a sequence of unique numbers (1, 2, 3, ...) to all the rows in each department. Since each sequence startw with 1, and the numbers are unique within a department, there will be exactly one row per departement that was assigned the numebr 1, and we''ll display that row.
    Here's how to code that:
    WITH     got_r_num     AS
         SELECT     d.dname
         ,     e.empno, e.ename, e.job, e.sal
         ,     ROW_NUMBER () OVER ( PARTITION BY  d.dname
                                   ORDER BY          e.ename
                           )         AS r_num
         FROM     scott.dept  d
         JOIN     scott.emp   e  ON   d.deptno = e.deptno
    SELECT       dname
    ,       empno, ename, job, sal
    FROM       got_r_num
    WHERE       r_num     = 1
    ORDER BY  dname
    ;Notice that he sub-query got_r_num is almost the same as the original query; only it has one additional column, r_num, in the SELECT clause, and the sub-qeury does not have an ORDER BY clause. (Sub-queries almost never have an ORDER BY clause.)
    The ROW_NUMBER function must have an ORDER BY clause. In this example, I used "ORDER BY ename", meaning that, within each department, the row with the first ename (in sort order) will get r_num=1. You can use any column, or expression, or expressions in the ORDER BY clause. You muight as well use something consistent and predictable, like ename, but if you really wanted arbitrary numbering you could use a constant in the analytic ORDER BY clause, e.g. "ORDER BY NULL".

  • Best approach to join multiple statistics tables into one

    I have read different approaches to join multiple statistics tables into one, they all have a column "productobjectid".
    I want to get all data for each product and put it to excel and output a jpg statistic with cfchart.
    How would you do this, the sql part?
    Thanks.

    A couple suggestions:
    1) when joining tables, its best to list both table/fields that you are joining in the FROM clause:
    FROM shopproductbehaviour_views INNER JOIN shopproductbehaviour_sails ON shopproductbehaviour_views.productobjectid = shopproductbehaviour_sails.productobjectid
    2) You add tables to a SQL join by placing another join statement after the SQL above:
    SELECT *
    FROM TableA INNER JOIN TableB on TableA.myField = TableB.myField
    INNER JOIN TableC on TableA.anotherField = TableC.anotherField
    3) If you have columns in the tables that are named the same, you can use column aliases to change the way they appear in your record set:
    SELECT TableA.datetimecreated 'tablea_create_date', TableB.datetimecreated 'tableb_create_date'
    4) Certainly not a requirement, but you might want to look into using <cfqueryparam> in your where clause:
    WHERE shopproductbehaviour_sails.productobjectid = <cfqueryparam cfsqltype="CF_SQL_VARCHAR" value="#all.productobjectid#">
     You might want to consider checking out one of the many tutorials on SQL available online.  Many of the questions you posed in your post are covered in pretty much every basic SQL tutorial.  Alternately, a good SQL book is worth its weight in gold for a beginning web applications developer.

  • One-to-many outer join in MView, is possible?

    Re: 10g R2
    Is it simply not possible to have fast refresh on outer joins that are 1-to-many relations? I have in this script a unique key addition to "fix" it, but it restricts something that I don't want restricted. If indeed this is how it should work, are there any strategies for improving performance for queries on this type of thing? The "fact_table" in this example is actually another materialized view with simple inner joins, so that works perfectly, but I was trying to improve query performance in this case too.
    Run the script w/ dbms output...all self contained within the schema.
    drop materialized view log on fact_Table;
    drop materialized view log on outer_detail;
    drop materialized view mview_test;
    drop table outer_detail cascade constraints;
    drop table fact_Table cascade constraints;
    create table fact_table (myid number primary key, fact_attrib varchar2(10));
    create table outer_detail (myid number primary key, outer_attrib varchar2(19), fact_table_id number, constraint fk_outer_to_Fact foreign key (fact_table_id) references fact_table(myid));
    CREATE MATERIALIZED VIEW LOG ON fact_table WITH ROWID;
    CREATE MATERIALIZED VIEW LOG ON outer_detail WITH ROWID;
    declare
        v_capabilities sys.ExplainMVArrayType ;
    begin
        dbms_mview.explain_mview('SELECT ft.rowid "ftrid", ' ||
           'od.rowid "odrid", ' ||
           'ft.myid fact_id, ' ||
           'od.myid outer_id, ' ||
           'ft.fact_attrib, ' ||
           'od.outer_attrib ' ||
      'FROM fact_table ft, outer_detail od ' ||
    'WHERE ft.myid = od.fact_table_id (+)', v_capabilities);
            dbms_output.put_line('ATTEMPT 1:');
            dbms_output.put_line('==============================================');
        for v_capability in (select capability_name, possible, related_text, msgtxt from table (v_capabilities))
        loop
            dbms_output.put_line('==============================================');
            dbms_output.put_line('==============================================');
            dbms_output.put_line(v_capability.capability_name);
            dbms_output.put_line(v_capability.possible);
            dbms_output.put_line(v_capability.related_text);
            dbms_output.put_line(v_capability.msgtxt);
        end loop;
    end;
    /*CREATE MATERIALIZED VIEW mview_test
    PARALLEL BUILD IMMEDIATE
    REFRESH FAST ON COMMIT WITH ROWID
    AS
    SELECT ft.rowid "ftrid",
           od.rowid "odrid",
           ft.myid fact_id,
           od.myid outer_id,
           ft.fact_attrib,
           od.outer_attrib
      FROM fact_table ft, outer_detail od
    WHERE ft.myid = od.fact_table_id (+);
    -- I'd like it to run without this constraint, is it not possible?
    alter table outer_detail add constraint unk_outer_detail unique (fact_table_id);
    declare
        v_capabilities sys.ExplainMVArrayType ;
    begin
        dbms_mview.explain_mview('SELECT ft.rowid "ftrid", ' ||
           'od.rowid "odrid", ' ||
           'ft.myid fact_id, ' ||
           'od.myid outer_id, ' ||
           'ft.fact_attrib, ' ||
           'od.outer_attrib ' ||
      'FROM fact_table ft, outer_detail od ' ||
    'WHERE ft.myid = od.fact_table_id (+)', v_capabilities);
            dbms_output.put_line('');
            dbms_output.put_line('');
            dbms_output.put_line('');
            dbms_output.put_line('ATTEMPT 2:');
            dbms_output.put_line('==============================================');
        for v_capability in (select capability_name, possible, related_text, msgtxt from table (v_capabilities))
        loop
            dbms_output.put_line('==============================================');
            dbms_output.put_line('==============================================');
            dbms_output.put_line(v_capability.capability_name);
            dbms_output.put_line(v_capability.possible);
            dbms_output.put_line(v_capability.related_text);
            dbms_output.put_line(v_capability.msgtxt);
        end loop;
    end;
    /Edited by: ORA-01435 on Sep 30, 2009 12:54 PM

    That's what I thought too. As far as I'm concerned, this is perfectly acceptable. Of course I'm in 10g R2, but:
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14223/basicmv.htm#sthref534
    I keep re-reading the rules, trying to see why it thinks I'm violating one of them. Might have to meta-link this one.
    Just ran this on a different box, ran fine. Seem to have configuration issues between the boxes.
    Edit: Just determined that the boxes that this doesn't work on have Oracle parameters for compatibility set to 10.1.0.2.0, I'll change them and check if it modifies behavior
    Edited by: ORA-01435 on Oct 1, 2009 7:44 AM

Maybe you are looking for

  • Wrong Planned Order dates - MRP Run

    Dear Experts, Please guide to resolve the following problem: I have uploaded the PIRs for 3 months. When I take the MRP run, the system is scheduling the planned orders for first 2 months only. For the 3rd month's PIR the planned order are created fo

  • SSL Negotiation Failure in WCF Service

    Hi, I have a WCF service hosted in IIS that is making a call to another cloud hosted service using HTTPS, however I get the error  'The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel'. I have c

  • Oracle Configurator Version

    DB Server: Oracle Linux 5.5 10.2.0.4.0 DB Version Application Server: Redhat EL 5.5 EBS 12.0.6 How does one figure out the version of "oracle configurator"? In a recent SR I was asked this question by Oracle support. Their method for me to find out w

  • Another lenovo (W530) doesn't charge a battery

    Hi folks! I was a happy owner of brand new W530 machine untill I mentioned that it doesn't charge the battery. The machine came to me with 94% charged batt and since then it got to 4% mark. Symptoms: -Lenovo Power Manager detects the batt, says it's

  • PC visitors to my iWeb site are suddenly unable to navigate pages

    AFter months of working fine, viewers with PCs tell me they cannot navigate from page to page on my Web site, published on Mac. They open to the Welcome page and are stuck there. I can navigate just fine on my Mac.