Help with self join

I need help to optimize this query - it's taking too long and the report times out - it jins to itself:
/* Formatted on 2005/03/01 14:12 (Formatter Plus v4.8.5) */
sELECT-- /*+ FIRST_ROWS */
--SELECT /*+ ROWID*/
aud.inv_id change_value_1, aud.inv_id change_value_2,
audit_inventory_reports_pkg.get_audit_inventory_desc
(aud.inv_id) item_modified,
x.trust_xfr_code original_value, aud.trust_xfr_code new_value,
aud.inf_app_user record_modified_by,
INITCAP (aud.inf_client_info) client_package_information,
aud.inf_module application, NULL record_created_on,
aud.inf_date_change record_modified_on,
DECODE (aud.inf_action_type,
'INSERT', 'TRUST TRANSFER ADDED',
'DELETE', 'TRUST TRANSFER REMOVED',
'TRUST TRANSFER MODIFIED'
) modification_type
FROM inf_p_inventory aud, inf_p_inventory x
WHERE aud.inf_action_type = 'UPDATE'
AND x.inv_id = aud.inv_id
AND x.trust_xfr_code != aud.trust_xfr_code
AND x.inf_action_type IN ('INSERT', 'UPDATE')
AND x.inf_id IN (SELECT MAX (y.inf_id)
FROM inf_p_inventory y
WHERE y.inv_id = aud.inv_id AND y.inf_id < aud.inf_id)
AND aud.inf_date_change BETWEEN TO_DATE ('20050201', 'YYYYMMDD')
AND TO_DATE ('20050228', 'YYYYMMDD') + .99999
and rownum<10
order by aud.inf_date_change
Plan:
Operation     Object Name     Rows     Bytes     Cost     Object Node     In/Out     PStart     PStop
SELECT STATEMENT Optimizer Mode=CHOOSE          1           10158
SORT ORDER BY          1      80      10151                     
COUNT STOPKEY                                        
FILTER                                        
HASH JOIN          1      80      10138                     
TABLE ACCESS BY INDEX ROWID     PAUDIT.INF_P_INVENTORY     24 K     1 M     4248                     
INDEX RANGE SCAN PAUDIT.INF_DTX_P_INV_IDX     74 K          200      
TABLE ACCESS FULL PAUDIT.INF_P_INVENTORY     1 M     19 M     5424      
SORT AGGREGATE          1      10                          TABLE ACCESS BY INDEX ROWID PAUDIT.INF_P_INVENTORY1 10 7           
INDEX RANGE SCAN PAUDIT.INF_PK_P_INV_IDX     4      3                     
Brand new statistics, good indexes:
CREATE TABLE INF_P_INVENTORY
INF_ID NUMBER(12) NOT NULL,
INF_ACTION_TYPE VARCHAR2(12 BYTE) NOT NULL,
INF_DATE_CHANGE DATE NOT NULL,
INF_ATLAS_PROC VARCHAR2(1 BYTE),
INF_ATTEMPTS NUMBER(12),
INF_CLIENT_INFO VARCHAR2(64 BYTE),
INF_DATE_XFRD DATE,
INF_DBL_DATE_XFRD DATE,
INF_APP_USER VARCHAR2(64 BYTE),
INF_DB_USER VARCHAR2(30 BYTE),
INF_DW_PROCESSED DATE,
INF_EXCEPTION_ID NUMBER(12),
INF_LOGON_TIME DATE,
INF_MACHINE VARCHAR2(64 BYTE),
INF_MODULE VARCHAR2(48 BYTE),
INF_OSUSER VARCHAR2(30 BYTE),
INF_PROGRAM VARCHAR2(48 BYTE),
INF_TERMINAL VARCHAR2(30 BYTE),
INV_ID NUMBER(12),
SMR_GLOBAL_NAME VARCHAR2(60 BYTE),
SMR_TIME_STAMP DATE,
PROJECT_ID VARCHAR2(4 BYTE),
UNIT_NUM VARCHAR2(6 BYTE),
SEASON_CODE VARCHAR2(3 BYTE),
SEASON_SEQ_NUM VARCHAR2(2 BYTE),
INV_STATUS_CODE VARCHAR2(3 BYTE),
ELEMENT VARCHAR2(3 BYTE),
ELEMENT_DESC VARCHAR2(35 BYTE),
OEB_CODE VARCHAR2(1 BYTE),
HOLD_CONTRACT VARCHAR2(1 BYTE),
CLUB_RELATED VARCHAR2(1 BYTE),
CLUB_USAGE_CREDITS NUMBER(12),
SELL_TYPE_CODE VARCHAR2(3 BYTE),
USAGE_TYPE_CODE VARCHAR2(3 BYTE),
MBR_CONTR_ID NUMBER(12),
HOLD_DATE DATE,
HOLD_EXP DATE,
EXP_DATE DATE,
HELD_BY_USER VARCHAR2(30 BYTE),
HOLD_REASON VARCHAR2(80 BYTE),
NUM_YRS_BOUGHT NUMBER(2),
ORIG_EXP_DATE DATE,
NUM_YRS_USED NUMBER(2),
FUTURE_EXP_DATE DATE,
APN_NUM VARCHAR2(20 BYTE),
RESALE_EXP_DATE DATE,
BOOK VARCHAR2(240 BYTE),
PAGE_NUM VARCHAR2(240 BYTE),
BOOK_PAGE_DATE DATE,
OEB_ACTIVE_DEACTIVE NUMBER(1),
GROUP_ID NUMBER(12),
STATE_INTERVAL_NUM VARCHAR2(20 BYTE),
STATE_UNIT_WK_NUM VARCHAR2(20 BYTE),
DATE_MODIFIED DATE,
MODIFIED_BY VARCHAR2(30 BYTE),
LAST_ASSESS_DATE DATE,
TRANSFER_PROJECT VARCHAR2(4 BYTE),
BATCH_ID NUMBER(12),
COURTHOUSE_CODE VARCHAR2(3 BYTE),
TRUST_XFR_CODE VARCHAR2(6 BYTE),
TRUST_XFR_CODE_REASON VARCHAR2(240 BYTE),
PTS_TRANSFER VARCHAR2(1 BYTE),
PTS_TRANSFER_DATE DATE,
TRANSFER_POINTS NUMBER,
TRANSFER_DATE DATE,
TRANSFER_BY VARCHAR2(30 BYTE),
TRANSFER_CODE VARCHAR2(1 BYTE),
LAST_ASSESSED_TO VARCHAR2(3 BYTE)
TABLESPACE xxx

how big is your inf_p_inventory table, i mean how many records does it has as compare to the other table?

Similar Messages

  • Need help with self join query

    Hello,
    I have table A with the following data
    oid parent_oid
    10 4
    4 2
    2 2
    12 6
    6 6
    parent_oid is the parent of oid. I'd like a query that shows the final parent of the oid. The result should show the following
    oid final parent
    10 2
    4 2
    2 2
    12 6
    6 6
    I'm using Oracle 10g. I'm familiar with self joins, but that alone will not do the job. Thanks!

    Hi,
    arizona9952 wrote:
    ... I'm familiar with self joins, but that alone will not do the job.You're absolutely right!
    A 2-way self join would work for rows have no parent, or rows that are directly connected to their final ancestor (such as oid=4), but not for anything farther away.
    A 3-way self-join would work for one more level away from the final row, but no more. That would be enough for the small set of sample data that you posted, but it would not work if you added a new row with parent_id=10.
    An N-way self-join would work for up to N+1 levels, but no more.
    You need something that can go any number of levels, such as CONNECT BY:
    SELECT     CONNECT_BY_ROOT oid     AS oid
    ,     parent_oid          AS final_parent
    FROM     a
    WHERE     CONNECT_BY_ISLEAF     = 1
    CONNECT BY     oid     = PRIOR parent_oid
         AND     oid     != parent_oid
    ;Edited by: Frank Kulash on Feb 22, 2010 7:09 PM
    Upon sober reflection, I think that a Top-Down query, like the one below, would be more efficient than a Bottom-Up query, like the one above:
    SELECT     oid
    ,     CONNECT_BY_ROOT     parent_oid     AS final_parent
    FROM     a
    START WITH     parent_oid     = oid
    CONNECT BY     parent_oid     = PRIOR oid
         AND     oid          != PRIOR oid
    ;

  • Help with self join query

    Hello people,
    I have the table MENUS on 9i with the folowing fields:
    MENU_ID, PARENT_ID, MENUNAME,...
    and some sample data:
    0,999999,ROOT
    7,0,NETWORK
    6,0,SERVICES
    100,0,CUSTOMERS
    74,7,MONITORING
    88889081,7,CONFIG
    88890006,7,TEST
    88890049,7 TEST II
    88889163,6,MAIL
    61,6,SMS
    So PARENT_ID shows under which menu the submenu exists.
    I need to create the below report:
    ROOT
    *NETWORK
    **CONFIG
    **TEST
    **TEST II
    *SERVICES
    **MAIL
    **SMS
    *CUSTOMERS
    Stars or any other way to identify the level depth will be very handful.
    Thank you in advance.

    Hi,
    Try to relate with this example on emp table.
    select empno,ename,level,sys_connect_by_path(ename,'/') as path
    from emp
    start with mgr is null
    connect by prior empno=mgrOutput
    EMPNO ENAME LEVEL PATH
    7839  KING      1       /KING
    7566  JONES    2      /KING/JONES
    7788  SCOTT   3      /KING/JONES/SCOTT
    7876  ADAMS   4      /KING/JONES/SCOTT/ADAMS
    7902  FORD     3      /KING/JONES/FORD
    7369  SMITH    4     /KING/JONES/FORD/SMITH
    7698  BLAKE    2     /KING/BLAKE
    7499  ALLEN    3     /KING/BLAKE/ALLEN
    7521  WARD    3    /KING/BLAKE/WARD
    7654  MARTIN  3    /KING/BLAKE/MARTIN Hope it helps
    CKLP

  • ADF Tree with Self Join

    Hi,
    I want to make an application using component tree with one table. This table has menu_id and menu_parent.
    I got a little problem when I use self joining table, it shown all parents and children.
    I want only the root folder (parent) to be shown first and then by opening the menu_parent, i should be able to see the menu_id folders.
    Can you please help me.
    Thanks

    Hi,
    you need to have a viewcriteria in your vo for selecting the parents one, then while selecting vo in datacontrols in AM you need to select your viewcriteria in your vo by editing it.
    Also you need to have a ViewLink between same viewobjects i.e menu_id->parent->id.
    See if this helps.
    Regards,
    Santosh,

  • Help with Inner Join query in SQL

    Hope someone can help with this, as this is quite an involved project for me, and I'm just about there with it.
    My table structure is :
    table_packages
    packageID
    package
    packageDetails
    etc
    table_destinations
    destinationID
    destination
    destinationDetails
    etc
    table_packagedestinations
    packageID
    destinationID
    ..so nothing that complicated.
    So the idea is that I can have a package details page which shows the details of the package, along any destinations linked to that package via the packagedestinations table.
    So this is the last part really - to get the page to display the destinations, but I'm missing something along the way....
    This is the PHP from the header, including my INNER JOIN query....
    PHP Code:
    <?php
    $ParampackageID_WADApackages = "-1";
    if (isset($_GET['packageID'])) {
      $ParampackageID_WADApackages = (get_magic_quotes_gpc()) ? $_GET['packageID'] : addslashes($_GET['packageID']);
    $ParamSessionpackageID_WADApackages = "-1";
    if (isset($_SESSION['WADA_Insert_packages'])) {
      $ParamSessionpackageID_WADApackages = (get_magic_quotes_gpc()) ? $_SESSION['WADA_Insert_packages'] : addslashes($_SESSION['WADA_Insert_packages']);
    $ParampackageID2_WADApackages = "-1";
    if (isset($_GET['packageID'])) {
      $ParampackageID2_WADApackages = (get_magic_quotes_gpc()) ? $_GET['packageID'] : addslashes($_GET['packageID']);
    mysql_select_db($database_connPackages, $connPackages);
    $query_WADApackages = sprintf("SELECT packageID, package, costperpax, duration, baselocation, category, dateadded, agerange, hotel, educational_tours, field_trips, corporate_outings, plant_visits, budget_package, rollingtours, teambuilding, description, offer FROM packages WHERE packageID = %s OR ( -1= %s AND packageID= %s)", GetSQLValueString($ParampackageID_WADApackages, "int"),GetSQLValueString($ParampackageID2_WADApackages, "int"),GetSQLValueString($ParamSessionpackageID_WADApackages, "int"));
    $WADApackages = mysql_query($query_WADApackages, $connPackages) or die(mysql_error());
    $row_WADApackages = mysql_fetch_assoc($WADApackages);
    $totalRows_WADApackages = mysql_num_rows($WADApackages);
    $colname_educationalDestinations = "1";
    if (isset($_GET['PackageID'])) {
      $colname_educationalDestinations = (get_magic_quotes_gpc()) ? packageID : addslashes(packageID);
    mysql_select_db($database_connPackages, $connPackages);
    $query_educationalDestinations = sprintf("SELECT * FROM destinations INNER JOIN (packages INNER JOIN packagedestinations ON packages.packageID = packagedestinations.packageID) ON destinations.destinationID = packagedestinations.destinationID WHERE packages.packageID = %s ORDER BY destination ASC", GetSQLValueString($colname_educationalDestinations, "int"));
    $educationalDestinations = mysql_query($query_educationalDestinations, $connPackages) or die(mysql_error());
    $row_educationalDestinations = mysql_fetch_assoc($educationalDestinations);
    $totalRows_educationalDestinations = mysql_num_rows($educationalDestinations);
    ?>
    And where I'm trying to display the destinations themselves, I have : 
    <table>
            <tr>
                     <td>Destinations :</td>
                </tr>
               <?php do { ?>
            <tr>
                 <td><?php echo $row_educationalDestinations['destination']; ?></td>
            </tr>
            <?php } while ($row_educationalDestinations = mysql_fetch_assoc($educationalDestinations)); ?>
    </table>
    If anyone could have a quick look and help me out that would be much appreciated - not sure if its my SQL at the top, or the PHP in the page, but either way it would be good to get it working. 
    Thanks.

    First off, you need to get the database tables so that there is a relationship between them.
    In fact, if there is a one to one relationship, then it may be better to store all of your information in one table such as
    table_packages
    packageID
    package
    packageDetails
    destination
    destinationDetails
    etc
    If there is a one to many relationship, then the following would be true
    packages
    packageID
    package
    packageDetails
    etc
    destinations
    destinationID
    packageID
    destination
    destinationDetails
    etc
    The above assumes that there are many destinations to one package with the relationship coloured orange.
    Once you have the above correct you can apply your query as follows
    SELECT *
    FROM packages
    INNER JOIN destinations
    ON packages.packageID = destinations.packageID
    WHERE packages.packageID = %s
    ORDER BY destination ASC
    The above query will show all packages with relevant destinations

  • Need help with outer joins

    I have the following table structure,
    Table - 1_
    ID | Information
    1 | abcadskasasa
    2 | asdasdasdasd
    3 | saeqdfdvsfcsc
    Table - 2_
    ID | PID
    1 | 12
    1 | 13
    2 | 14
    1 | 15
    1 | 16
    2 | 12
    Table - 3_
    ID | PARID
    1 | 12
    2 | 14
    1 | 15
    Now I want to select for each ID in table 1, the count of number of PID from table 2 and count of number of PARID from table 3.
    Desired output:_
    ID | COUNT_PID | COUNT_PARID
    1 | 4 | 2
    2 | 2 | 1
    3 | 0 | 0
    Could anyone please help me out with this. I am trying to make use of outer joins, but as I work mostly on the front end so, not able to come up with a proper solution for the above.
    Thanks in advance,
    Tejas

    Hi, Tejas,
    You might have been doing the outer join correctly.
    There's another problem here: joining table_1 to two other tables with which it has a one-to-many relationship.
    If you were joining table_1 to just one other table, you could say:
    SELECT       t1.id
    ,       COUNT (t2.pid)     AS count_pid
    FROM              table_1     t1
    LEFT OUTER JOIN  table_2     t2     ON     t1.id     = t2.id
    GROUP BY  t1.id
    ORDER BY  t1.id;You could have done the exact same thing with table_3 instead of table_2.
    But you can't do the same thing with both table_2 and table_3 at the same time: that would be like cross-joining table_2 and table_3. Instead of showing id=1 having count_pid=4 and count_parid=2, you would get cout_pid=8 and count_parid=8 (since 8 = 4 * 2).
    You can do a separate GROUP BY on (at least) one of the tables.
    This gets the right results. In the main query, there is only one one-to-many relationship.
    WITH  t3_summary     AS
         SELECT    id
         ,       COUNT (parid)     AS count_parid
         FROM       table_3
         GROUP BY  id
    SELECT       t1.id
    ,       COUNT (t2.pid)     AS count_pid
    ,       MAX (t3.count_parid)     AS count_parid
    FROM              table_1     t1
    LEFT OUTER JOIN  table_2     t2     ON     t1.id     = t2.id
    LEFT OUTER JOIN      t3_summary     t3     ON     t1.id     = t3.id
    GROUP BY  t1.id
    ORDER BY  t1.id;

  • Help with outer joins in Oracle!!

    so far this is what i've come up with and the code below does not work. Can anyone please help me on how the sytanx of left joins and how to use multiple left joins in a single query in oracle?
    SELECT a.*, b.Position_CD, c.Skill_CD, d.Team_Name, d.Team_Country, d.Club, e.Structure_Name
    FROM Roster a, Roster_position b, roster_skill c, Team d, Team_Structure e
    where (a.Roster_ID = ((b.Roster_ID= c.Roster_Id(+)) b.roster_id(+)).......
    I dont' know how to add more left joins!
    Here is the query I'm trying to duplicate (which is a query from Ms Access databaase which works fine).
    SELECT a.*, b.Position_CD, c.Skill_CD, d.Team_Name, d.Team_Country, d.Club, e.Structure_Name
    from ((Roster a LEFT JOIN (Roster_Position b LEFT JOIN Roster_Skill c ON b.Roster_ID=c.Roster_ID) ON a.Roster_ID=b.Roster_ID) LEFT JOIN Team d ON a.Team_CD=d.Team_CD) LEFT JOIN Team_Structure e ON a.Team_Structure_CD=e.Team_Structure_CD
    ORDER BY a.Roster_Id;
    Any help or comments are greatly appreciated

    First,
    I am not one of the leading SQL brains here...but I'm taking a stab, nonetheless.
    Second,
    Here's my best guess - and it seems to me that it should work as there are not two outer joins between any two tables. I hope I decoded your joins correctly - quite a mess that Access syntax!
    SELECT a.*, b.position_cd, c.skill_cd, d.team_name, d.team_country, d.club, e.structure_name
    FROM ROSTER a, ROSTER_POSITION b, ROSTER_SKILL c, TEAM d, TEAM_STRUCTURE e
    WHERE a.roster_id = b.roster_id(+)
    AND b.roster_id = c.roster_id(+)
    AND a.team_cd = d.team_cd(+)
    AND a.team_structure = e.team_structure(+);Third,
    As an architect-dude, it seems to me that you have a serious
    modeling problem to need so many outer joins in such a basic
    grab of data. In any scale other than minute, the performance
    of this model will suffer dramatically. Specifically, why can't
    ROSTER have an equijoin with TEAM and with TEAM_STRUCTURE - as they
    appear to be lookup tables...
    Good Luck
    (I'm certain you'll get better SQL from the others),
    Michael O'Neill
    Publisher of the PigiWiki
    clever-idea.com

  • Need help with Update Join Query

    Hello, I am trying to update PID of #child table with PID of #parent table if "lastname & firstname are matches in both table" but my update query is giving some error. Please help and correct the update query. I am also trying to remove any
    blank space from starting and ending.
    drop table #parent,#child
    create table #parent (PID varchar(10), lastname varchar(50), firstname varchar(50))
    insert into #parent values ('100','Josheph','Sumali')
    insert into #parent values ('400','Karen','Hunsa')
    insert into #parent values ('600','Mursan  ','  Terry')
    create table #child (PID varchar(10), lastname varchar(50), firstname varchar(50))
    insert into #child values ('2','Josheph ','Sumali   ')
    insert into #child values ('5','Karen','Kunsi')
    insert into #child values ('6','Mursan ','Terry ')
    Update #child
    set PID = p.PID
    from #child C Join
    #parent p ON c.LTRIM(RTRIM(lastname) = p.LTRIM(RTRIM(lastname)
    AND c.LTRIM(RTRIM(firstname) = p.LTRIM(RTRIM(firstname)
    /* Requested Output */
    PID        lastname      firstname
    100        Josheph       Sumali
    600        Mursan        Terry

    create table #parent (PID varchar(10), lastname varchar(50), firstname varchar(50))
    insert into #parent values ('100','Josheph','Sumali')
    insert into #parent values ('400','Karen','Hunsa')
    insert into #parent values ('600','Mursan ',' Terry')
    create table #child (PID varchar(10), lastname varchar(50), firstname varchar(50))
    insert into #child values ('2','Josheph ','Sumali ')
    insert into #child values ('5','Karen','Kunsi')
    insert into #child values ('6','Mursan ','Terry ')
    Merge #child as t
    Using #parent as p ON (LTRIM(RTRIM(t.lastname)) = LTRIM(RTRIM(p.lastname))
    AND LTRIM(RTRIM(t.firstname)) = LTRIM(RTRIM(p.firstname)) )
    When Matched Then
    Update
    set PID = p.PID;
    update #child
    Set lastname=LTRIM(RTRIM(lastname)), firstname= LTRIM(RTRIM(firstname));
    update #parent
    Set lastname=LTRIM(RTRIM(lastname)), firstname = LTRIM(RTRIM(firstname));
    select * from #child
    select * from #parent
    drop table #parent,#child

  • Help with inner join PLEASE IGNORE

    Hi I was doing a select with a subquery but I need that the where clause check to values so I couldn't get it so I decided to create a INNER JOIN
    Before
    insert into BPMTEMP (select * from ODS_VIEWER.BAN_EVENTOS_CONFIRMACION@DBLINK1 where id_solicitud and accion not in (select (id_solicitud, accion) from ODS_VIEWER.BAN_CONFIRMA_RESPUESTA@DBLINK1) and rownum <=200);but the problem with the inner join is that it doesn't accept me the external database source
    insert into BPMTEMP (select ODS_VIEWER.BAN_EVENTOS_CONFIRMACION@DBLINK1.*, ODS_VIEWER.BAN_CONFIRMA_RESPUESTA@DBLINK1.*
    from ODS_VIEWER.BAN_EVENTOS_CONFIRMACION@DBLINK1
    INNER JOIN ODS_VIEWER.BAN_CONFIRMA_RESPUESTA@DBLINK1
    ON [email protected]_solicitud = [email protected]_solicitud
    ON [email protected] = [email protected]
    AND rownum <=200); it shows an:
    ORA-02084:
         database name is missing a component
    Cause:      supplied database name cannot contain a leading '.', trailing '.' or '@', or two '.' or '@' in a row.
    how can I solve this????
    thanks for your help
    Edited by: Diego Guillen on 29/12/2009 11:14 AM

    Hi
    Please remove the @dblink stuff in the column descrptions or use a table alias. This should help.
    drop database link lokal;
    create database link lokal
       CONNECT TO whateveruserineed IDENTIFIED BY whateverthing
       USING 'lokal11g';
    select HR.COUNTRIES.*  from HR.COUNTRIES@lokal;
    select x.* from HR.COUNTRIES@lokal x;And as Dan Morgans says, pls. post you ? in the right forum next time :-))
    Mette

  • Help with outer join

    I have two tables:
    PS and Entity whose data are as follows
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-DEC-08','DD-MON-RR HH.MI.SSXFF AM'),1);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-DEC-08','DD-MON-RR HH.MI.SSXFF AM'),3);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-DEC-08','DD-MON-RR HH.MI.SSXFF AM'),6);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-DEC-08','DD-MON-RR HH.MI.SSXFF AM'),10);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-DEC-08','DD-MON-RR HH.MI.SSXFF AM'),13);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('27-JAN-09','DD-MON-RR HH.MI.SSXFF AM'),13);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('27-JAN-09','DD-MON-RR HH.MI.SSXFF AM'),10);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('27-JAN-09','DD-MON-RR HH.MI.SSXFF AM'),6);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('27-JAN-09','DD-MON-RR HH.MI.SSXFF AM'),3);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('27-JAN-09','DD-MON-RR HH.MI.SSXFF AM'),1);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-FEB-09','DD-MON-RR HH.MI.SSXFF AM'),13);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-FEB-09','DD-MON-RR HH.MI.SSXFF AM'),10);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-FEB-09','DD-MON-RR HH.MI.SSXFF AM'),6);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-FEB-09','DD-MON-RR HH.MI.SSXFF AM'),3);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-FEB-09','DD-MON-RR HH.MI.SSXFF AM'),1);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('30-MAR-09','DD-MON-RR HH.MI.SSXFF AM'),1);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('30-MAR-09','DD-MON-RR HH.MI.SSXFF AM'),3);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('30-MAR-09','DD-MON-RR HH.MI.SSXFF AM'),6);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('30-MAR-09','DD-MON-RR HH.MI.SSXFF AM'),10);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('30-MAR-09','DD-MON-RR HH.MI.SSXFF AM'),13);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('28-APR-09','DD-MON-RR HH.MI.SSXFF AM'),13);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('28-APR-09','DD-MON-RR HH.MI.SSXFF AM'),10);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('28-APR-09','DD-MON-RR HH.MI.SSXFF AM'),6);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('28-APR-09','DD-MON-RR HH.MI.SSXFF AM'),3);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('28-APR-09','DD-MON-RR HH.MI.SSXFF AM'),1);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('29-MAY-09','DD-MON-RR HH.MI.SSXFF AM'),14);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('29-MAY-09','DD-MON-RR HH.MI.SSXFF AM'),9);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('29-MAY-09','DD-MON-RR HH.MI.SSXFF AM'),13);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('29-MAY-09','DD-MON-RR HH.MI.SSXFF AM'),10);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('29-MAY-09','DD-MON-RR HH.MI.SSXFF AM'),6);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('29-MAY-09','DD-MON-RR HH.MI.SSXFF AM'),3);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('29-MAY-09','DD-MON-RR HH.MI.SSXFF AM'),1);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-JUN-09','DD-MON-RR HH.MI.SSXFF AM'),13);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-JUN-09','DD-MON-RR HH.MI.SSXFF AM'),10);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-JUN-09','DD-MON-RR HH.MI.SSXFF AM'),6);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-JUN-09','DD-MON-RR HH.MI.SSXFF AM'),3);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-JUN-09','DD-MON-RR HH.MI.SSXFF AM'),1);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('28-JUL-09','DD-MON-RR HH.MI.SSXFF AM'),14);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('28-JUL-09','DD-MON-RR HH.MI.SSXFF AM'),9);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('28-JUL-09','DD-MON-RR HH.MI.SSXFF AM'),13);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('28-JUL-09','DD-MON-RR HH.MI.SSXFF AM'),10);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('28-JUL-09','DD-MON-RR HH.MI.SSXFF AM'),6);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('28-JUL-09','DD-MON-RR HH.MI.SSXFF AM'),3);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('28-JUL-09','DD-MON-RR HH.MI.SSXFF AM'),1);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-AUG-09','DD-MON-RR HH.MI.SSXFF AM'),14);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-AUG-09','DD-MON-RR HH.MI.SSXFF AM'),9);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-AUG-09','DD-MON-RR HH.MI.SSXFF AM'),13);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-AUG-09','DD-MON-RR HH.MI.SSXFF AM'),10);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-AUG-09','DD-MON-RR HH.MI.SSXFF AM'),6);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-AUG-09','DD-MON-RR HH.MI.SSXFF AM'),3);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-AUG-09','DD-MON-RR HH.MI.SSXFF AM'),1);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('25-SEP-09','DD-MON-RR HH.MI.SSXFF AM'),14);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('25-SEP-09','DD-MON-RR HH.MI.SSXFF AM'),9);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('25-SEP-09','DD-MON-RR HH.MI.SSXFF AM'),13);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('25-SEP-09','DD-MON-RR HH.MI.SSXFF AM'),10);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('25-SEP-09','DD-MON-RR HH.MI.SSXFF AM'),6);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('25-SEP-09','DD-MON-RR HH.MI.SSXFF AM'),3);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('25-SEP-09','DD-MON-RR HH.MI.SSXFF AM'),1);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-OCT-09','DD-MON-RR HH.MI.SSXFF AM'),14);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-OCT-09','DD-MON-RR HH.MI.SSXFF AM'),9);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-OCT-09','DD-MON-RR HH.MI.SSXFF AM'),13);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-OCT-09','DD-MON-RR HH.MI.SSXFF AM'),10);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-OCT-09','DD-MON-RR HH.MI.SSXFF AM'),6);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-OCT-09','DD-MON-RR HH.MI.SSXFF AM'),3);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('26-OCT-09','DD-MON-RR HH.MI.SSXFF AM'),1);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('24-NOV-09','DD-MON-RR HH.MI.SSXFF AM'),14);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('24-NOV-09','DD-MON-RR HH.MI.SSXFF AM'),9);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('24-NOV-09','DD-MON-RR HH.MI.SSXFF AM'),13);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('24-NOV-09','DD-MON-RR HH.MI.SSXFF AM'),10);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('24-NOV-09','DD-MON-RR HH.MI.SSXFF AM'),6);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('24-NOV-09','DD-MON-RR HH.MI.SSXFF AM'),3);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('24-NOV-09','DD-MON-RR HH.MI.SSXFF AM'),1);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('25-DEC-09','DD-MON-RR HH.MI.SSXFF AM'),9);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('25-DEC-09','DD-MON-RR HH.MI.SSXFF AM'),13);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('25-DEC-09','DD-MON-RR HH.MI.SSXFF AM'),10);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('25-DEC-09','DD-MON-RR HH.MI.SSXFF AM'),6);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('25-DEC-09','DD-MON-RR HH.MI.SSXFF AM'),3);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('25-DEC-09','DD-MON-RR HH.MI.SSXFF AM'),1);
    Insert into PS (DATE_TIME,ENTITY_ID) values (to_timestamp('25-DEC-09','DD-MON-RR HH.MI.SSXFF AM'),14);
    Entity:
    Insert into ENTITY (ENTITY_ID,ENTITY_ADDRESS) values (1,'AAA');
    Insert into ENTITY (ENTITY_ID,ENTITY_ADDRESS) values (3,'CCC');
    Insert into ENTITY (ENTITY_ID,ENTITY_ADDRESS) values (6,'DDD');
    Insert into ENTITY (ENTITY_ID,ENTITY_ADDRESS) values (9,'EEE');
    Insert into ENTITY (ENTITY_ID,ENTITY_ADDRESS) values (10,'FFF');
    Insert into ENTITY (ENTITY_ID,ENTITY_ADDRESS) values (13,'GGG');
    Insert into ENTITY (ENTITY_ID,ENTITY_ADDRESS) values (14,'HHH');
    I want to display data for each entity available in entity table
    What is wrong with this query??
    Select ps.date_time,ps.entity_id,et.entity_id from entity et left outer join PS ps on (et.entity_id = ps.entity_id)
    This query gives me result like
    26-DEC-08     1     1
    26-DEC-08     3     3
    26-DEC-08     6     6
    26-DEC-08     10     10
    26-DEC-08     13     13
    27-JAN-09     13     13
    27-JAN-09     10     10
    27-JAN-09     6     6
    27-JAN-09     3     3
    27-JAN-09     1     1...
    But for 26-Dec-08, i want to display
    26-DEC-08     1     1
    26-DEC-08     3     3
    26-DEC-08     6     6
    26-DEC-08     10     10
    26-DEC-08     13     13
    26-DEC-08 NULL 9
    26-DEC-09 NULL 14
    27-JAN-09     13     13
    27-JAN-09     10     10
    27-JAN-09     6     6
    27-JAN-09     3     3
    27-JAN-09     1     1
    But the unmatching ids are not displaying when i am using the outer join..please help me..

    Almost there.
    In this case you need a partitioned outer join, partitioning by date_time:
    SQL> Select ps.date_time
      2       , ps.entity_id
      3       , et.entity_id
      4    from ps partition by (ps.date_time)
      5         right outer join entity et on (et.entity_id = ps.entity_id)
      6  /
    DATE_TIME                                 ENTITY_ID  ENTITY_ID
    26-12-08 00:00:00,000000                          1          1
    26-12-08 00:00:00,000000                          3          3
    26-12-08 00:00:00,000000                          6          6
    26-12-08 00:00:00,000000                                     9
    26-12-08 00:00:00,000000                         10         10
    26-12-08 00:00:00,000000                         13         13
    26-12-08 00:00:00,000000                                    14
    27-01-09 00:00:00,000000                          1          1
    27-01-09 00:00:00,000000                          3          3
    27-01-09 00:00:00,000000                          6          6
    27-01-09 00:00:00,000000                                     9
    27-01-09 00:00:00,000000                         10         10
    27-01-09 00:00:00,000000                         13         13
    27-01-09 00:00:00,000000                                    14
    26-02-09 00:00:00,000000                          1          1
    26-02-09 00:00:00,000000                          3          3
    26-02-09 00:00:00,000000                          6          6
    26-02-09 00:00:00,000000                                     9
    26-02-09 00:00:00,000000                         10         10
    26-02-09 00:00:00,000000                         13         13
    26-02-09 00:00:00,000000                                    14
    30-03-09 00:00:00,000000                          1          1
    30-03-09 00:00:00,000000                          3          3
    30-03-09 00:00:00,000000                          6          6
    30-03-09 00:00:00,000000                                     9
    30-03-09 00:00:00,000000                         10         10
    30-03-09 00:00:00,000000                         13         13
    30-03-09 00:00:00,000000                                    14
    28-04-09 00:00:00,000000                          1          1
    28-04-09 00:00:00,000000                          3          3
    28-04-09 00:00:00,000000                          6          6
    28-04-09 00:00:00,000000                                     9
    28-04-09 00:00:00,000000                         10         10
    28-04-09 00:00:00,000000                         13         13
    28-04-09 00:00:00,000000                                    14
    29-05-09 00:00:00,000000                          1          1
    29-05-09 00:00:00,000000                          3          3
    29-05-09 00:00:00,000000                          6          6
    29-05-09 00:00:00,000000                          9          9
    29-05-09 00:00:00,000000                         10         10
    29-05-09 00:00:00,000000                         13         13
    29-05-09 00:00:00,000000                         14         14
    26-06-09 00:00:00,000000                          1          1
    26-06-09 00:00:00,000000                          3          3
    26-06-09 00:00:00,000000                          6          6
    26-06-09 00:00:00,000000                                     9
    26-06-09 00:00:00,000000                         10         10
    26-06-09 00:00:00,000000                         13         13
    26-06-09 00:00:00,000000                                    14
    28-07-09 00:00:00,000000                          1          1
    28-07-09 00:00:00,000000                          3          3
    28-07-09 00:00:00,000000                          6          6
    28-07-09 00:00:00,000000                          9          9
    28-07-09 00:00:00,000000                         10         10
    28-07-09 00:00:00,000000                         13         13
    28-07-09 00:00:00,000000                         14         14
    26-08-09 00:00:00,000000                          1          1
    26-08-09 00:00:00,000000                          3          3
    26-08-09 00:00:00,000000                          6          6
    26-08-09 00:00:00,000000                          9          9
    26-08-09 00:00:00,000000                         10         10
    26-08-09 00:00:00,000000                         13         13
    26-08-09 00:00:00,000000                         14         14
    25-09-09 00:00:00,000000                          1          1
    25-09-09 00:00:00,000000                          3          3
    25-09-09 00:00:00,000000                          6          6
    25-09-09 00:00:00,000000                          9          9
    25-09-09 00:00:00,000000                         10         10
    25-09-09 00:00:00,000000                         13         13
    25-09-09 00:00:00,000000                         14         14
    26-10-09 00:00:00,000000                          1          1
    26-10-09 00:00:00,000000                          3          3
    26-10-09 00:00:00,000000                          6          6
    26-10-09 00:00:00,000000                          9          9
    26-10-09 00:00:00,000000                         10         10
    26-10-09 00:00:00,000000                         13         13
    26-10-09 00:00:00,000000                         14         14
    24-11-09 00:00:00,000000                          1          1
    24-11-09 00:00:00,000000                          3          3
    24-11-09 00:00:00,000000                          6          6
    24-11-09 00:00:00,000000                          9          9
    24-11-09 00:00:00,000000                         10         10
    24-11-09 00:00:00,000000                         13         13
    24-11-09 00:00:00,000000                         14         14
    25-12-09 00:00:00,000000                          1          1
    25-12-09 00:00:00,000000                          3          3
    25-12-09 00:00:00,000000                          6          6
    25-12-09 00:00:00,000000                          9          9
    25-12-09 00:00:00,000000                         10         10
    25-12-09 00:00:00,000000                         13         13
    25-12-09 00:00:00,000000                         14         14
    91 rijen zijn geselecteerd.Partitioned outer join became available somewhere during version 10. They are described here: http://download.oracle.com/docs/cd/B28359_01/server.111/b28314/tdpdw_sql.htm#TDPDW00736
    Regards,
    Rob.

  • Need help with query joining several tables into a single return line

    what i have:
    tableA:
    puid, task
    id0, task0
    id1, task1
    id2, task2
    tableB:
    puid, seq, state
    id0, 0, foo
    id0, 1, bar
    id0, 2, me
    id1, 0, foo
    id2, 0, foo
    id2, 1, bar
    tableC:
    puid, seq, date
    id0, 0, 12/21
    id0, 1, 12/22
    id0, 2, 12/22
    id1, 0, 12/23
    id2, 0, 12/22
    id2, 1, 12/23
    what i'd like to return:
    id0, task0, 12/21, 12/22, 12/22
    id1, task1, 12/23, N/A, N/A
    id2, task2, 12/22, 12/23, N/A
    N/A doesn't mean return the string "N/A"... it just means there was no value, so we don't need anything in this column (null?)
    i can get output like below through several joins, however i was hoping to condense each "id" into a single line...
    id0, task0, 12/21
    id0, task0, 12/22
    id0, task0, 12/23
    id1, task1, 12/23
    is this possible fairly easily?
    Edited by: user9979830 on Mar 29, 2011 10:53 AM
    Edited by: user9979830 on Mar 29, 2011 10:58 AM

    Hi,
    Welcome to the forum!
    user9979830 wrote:
    what i have:...Thanks for posting that so clearly!
    Whenever you have a question, it's even better if you post CREATE TABLE and INSERT statements for your sample data, like this:
    CREATE TABLE     tablea
    (       puid     VARCHAR2 (5)
    ,     task     VARCHAR2 (5)
    INSERT INTO tablea (puid, task) VALUES ('id0',  'task0');
    INSERT INTO tablea (puid, task) VALUES ('id1',  'task1');
    INSERT INTO tablea (puid, task) VALUES ('id2',  'task2');
    CREATE TABLE     tablec
    (       puid     VARCHAR2 (5)
    ,     seq     NUMBER (3)
    ,     dt     DATE          -- DATE is not a good column name
    INSERT INTO tablec (puid, seq, dt) VALUES ('id0',  0,  DATE '2010-12-21');
    INSERT INTO tablec (puid, seq, dt) VALUES ('id0',  1,  DATE '2010-12-22');
    INSERT INTO tablec (puid, seq, dt) VALUES ('id0',  2,  DATE '2010-12-22');
    INSERT INTO tablec (puid, seq, dt) VALUES ('id1',  0,  DATE '2010-12-23');
    INSERT INTO tablec (puid, seq, dt) VALUES ('id2',  0,  DATE '2010-12-22');
    INSERT INTO tablec (puid, seq, dt) VALUES ('id2',  1,  DATE '2010-12-23');This way, people can re-create the problem and test their ideas.
    It doesn't look like tableb plays any role in this problem, so I didn't post it.
    Explain how you get the results from that data. For example, why do you want this row in the results:
    PUID  TASK  DT1        DT2        DT3
    id0   task0 12/21/2010 12/22/2010 12/22/2010rather than, say
    PUID  TASK  DT1        DT2        DT3
    id0   task0 12/22/2010 12/21/2010 12/22/2010? Does 12/21 have to go in the first column because it is the earliest date, or is it because 12/21 is related to the lowest seq value? Or do you even care about the order, just as long as all 3 dates are shown?
    Always say what version of Oracle you're uisng. The query below will work in Oracle 9 (and up), but starting in Oracle 11, the SELECT ... PIVOT feature could help you.
    i can get output like below through several joins, however i was hoping to condense each "id" into a single line... Condensing the output, so that there's only one line for each puid, sounds like a job for "GROUP BY puid":
    WITH     got_r_num     AS
         SELECT     puid
         ,     dt
         ,     ROW_NUMBER () OVER ( PARTITION BY  puid
                                   ORDER BY          seq          -- and/or dt
                           )         AS r_num
         FROM    tablec
    --     WHERE     ...     -- If you need any filtering, put it here
    SELECT       a.puid
    ,       a.task
    ,       MIN (CASE WHEN r.r_num = 1 THEN r.dt END)     AS dt1
    ,       MIN (CASE WHEN r.r_num = 2 THEN r.dt END)     AS dt2
    ,       MIN (CASE WHEN r.r_num = 3 THEN r.dt END)     AS dt3
    ,       MIN (CASE WHEN r.r_num = 4 THEN r.dt END)     AS dt4
    FROM       tablea    a
    JOIN       got_r_num r  ON   a.puid  = r.puid
    GROUP BY  a.puid
    ,            a.task
    ORDER BY  a.puid
    ;I'm guessing that you want the dates arranged by seq; that is, for each puid, the date related to the lowest seq comes first, regardless of whther that date is the earliest date for that puid or not. If that's not what you need, then change the analytic ORDER BY clause.
    This does not assume that the seq values are always consecutive integers (0, 1, 2, ...) for each puid. You can skip, or even duplicate values. However, if the values are always consecutive integers, starting from 0, then you could simplify this. You won't need a sub-query at all; just use seq instead of r_num in the main query.
    Here's the output I got from the query above:
    PUID  TASK  DT1        DT2        DT3        DT4
    id0   task0 12/21/2010 12/22/2010 12/22/2010
    id1   task1 12/23/2010
    id2   task2 12/22/2010 12/23/2010As posted, the query will display the first 4 dts for each puid.
    If there are fewer than 4 dts for a puid, the query will still work. It will leave some columns NULL at the end.
    If there are more than 4 dts for a puid, the query will still work. It will display the first 4, and ignore the others.
    There's nothing special about the number 4; you could make it 3, or 5, or 35, but whatever number you choose, you have to hard-code that many columns into the query, and always get that many columns of output.
    For various ways to deal with a variable number of pivoted coolumns, see the following thread:
    PL/SQL
    This question actually doesn't have anything to do with SQL*Plus; it's strictly a SQL question, and SQL questions are best posted on the "SQL and PL/SQL" forum:
    PL/SQL
    If you're not sure whether a question is more of a SQL question or a SQL*Plus question, then post it on the SQL forum. Many more people pay attention to that forum than to this one.

  • Help with Multiple-Join Query

    I have three tables, photos, comments and prices. Their
    structures (abbreviated) are as follows:
    photos
    photoID
    photoTitle
    prices
    priceID
    priceValue
    photoID_fk
    comments
    commentID
    commentText
    photoID_fk
    What I need to do is be able to display a list of photos with
    their correlating prices and comments, like so:
    Photo 1
    Price 1
    Price 2
    Comment 1
    comment 2
    Photo 2
    Price 1
    Price 2
    Photo 3
    Price 1
    Price 2
    Comment 1
    Notice that while each photo will always have the same number
    of "price" values, some might have comments and some might not.
    I will list the code that I have thus far, but let me briefly
    explain what is happening. With the setup I currently have, the
    photos display in the proper order with their proper price values
    and comments (if any). Unfortunately, on the ones WITH comments,
    the list of prices duplicates to match the number of comments
    returned. So, if Photo 1 has two comments, it will return "Price 1
    Price 2 Price 1 Price 2" for the output of the price section.
    I have been pulling my hair out over this, and any help that
    anyone could provide would be greatly appreciated and will
    potentially save my life.

    Dan--
    Thanks, as always, for your response. Your solution solved
    the problem!
    As to my database needs, the comments are related only to the
    photos.
    Basically, I have a a table that holds all information about
    photos in a gallery. I have another table which holds all the
    comments that users make about the photos. Finally, each and every
    photo has 8 sizes (all the same) for sale. So, I don't think the
    MTM relationship is there.
    Initially, I was simply going to put Size1, Size2, etc. in
    the photos table. However, my client wants to be able to add and/or
    remove sizes in the future. Therefore, I thought it would be easier
    if every photo was given "x" number of entries in the prices table,
    where "x" is the number of total price categories (currently 8).
    I don't want to monopolize more of your time, but if you have
    a second, I would be interested in hearing a more developed
    explanation of the restructuring that you proposed at the end of
    your last response. If you do not have time, I understand of
    course.
    Thanks a million for your help on this!

  • Need help with a JOIN query

    Hi,
    I am looking for the following result:
    PROVIDER_ID     SPECIALTY     BUCKET     CODE     RATING     FEE
         1     FP                 EM     100     9     20
         1     FP                 SP     300     15     0
         1     INFUS                 EM     100     3     20
         1     INFUS                 EM     200     6     15The base tables are provided below in the with clause. What I am trying to do is, where "code" matches show the fee from t1 else show 0.
    I tried a few variotions but just can't seem to get it right.
    with t1 as
    select 1 as provider_id, 100 as code, 20 as fee, 10 as default_multiplier from dual union all
    select 1 as provider_id, 200 as code, 15 as fee, 30 as default_multiplier from dual
    , t2 as
    select 100 as code, 'INFUS' AS specialty, 'EM' AS bucket, 3 as rating from dual union all
    select 200 as code, 'INFUS' AS specialty, 'EM' AS bucket, 6 as rating from dual union all
    select 100 as code, 'FP' AS specialty, 'EM' AS bucket, 9 as rating from dual union all
    select 300 as code, 'FP' AS specialty, 'SP' AS bucket, 15 as rating from dual
    SELECT   t1.provider_id
           , t2.specialty
           , t2.bucket
           , t2.code
           , t2.rating
           , t1.fee
    FROM     t1, t2
    ORDER BY 1, 2, 3Any help will be appreciated.
    Thanks.

    Could I possibly add one more twist to this.
    The current result:
    PROVIDER_ID SPECI BU       CODE     RATING        FEE
              1 FP    EM        100          9         20
              1 FP    SP        300         15          0
              1 INFUS EM        100          3         20
              1 INFUS EM        200          6         75
              2 FP    EM        100          9         40
              2 FP    SP        300         15          0
              2 INFUS EM        100          3         40
              2 INFUS EM        200          6          0
              3 FP    EM        100          9          0
              3 FP    SP        300         15          0
              3 INFUS EM        100          3          0
              3 INFUS EM        200          6         60The current code:
    with t1 as
    select 1 as provider_id, 100 as code, 20 as fee, 10 as default_multiplier from dual union all
    select 1 as provider_id, 200 as code, 75 as fee, 10 as default_multiplier from dual union all
    select 1 as provider_id, 500 as code, 75 as fee, 10 as default_multiplier from dual union all
    select 2 as provider_id, 100 as code, 40 as fee, 20 as default_multiplier from dual union all
    select 3 as provider_id, 200 as code, 60 as fee, 30 as default_multiplier from dual
    , t2 as
    select 100 as code, 'INFUS' AS specialty, 'EM' AS bucket, 3 as rating from dual union all
    select 200 as code, 'INFUS' AS specialty, 'EM' AS bucket, 6 as rating from dual union all
    select 100 as code, 'FP' AS specialty, 'EM' AS bucket, 9 as rating from dual union all
    select 300 as code, 'FP' AS specialty, 'SP' AS bucket, 15 as rating from dual
    , t3 as
    SELECT   t1.provider_id
           , t2.specialty
           , t2.bucket
           , t2.code
           , t2.rating
           , CASE t1.code
                WHEN t2.code
                   THEN t1.fee
                ELSE 0
             END AS fee
           , RANK () OVER (PARTITION BY t1.provider_id, t2.specialty, t2.bucket, t2.code ORDER BY CASE t1.code
                 WHEN t2.code
                    THEN t1.fee
                 ELSE 0
              END DESC) AS the_rank
        FROM t1
           , t2
    SELECT DISTINCT provider_id
                  , specialty
                  , bucket
                  , code
                  , rating
                  , fee
               FROM t3
              WHERE the_rank = 1
           ORDER BY 1
                  , 2
                  , 3
                  , 4I added the code 500 to t1. Howevere, I don't want this code to show up in the result becuase it is does not exist in t2.
    I also added code 200 to t1, to see if that shows properly.
    I had to do the rank, becuase I need the proper count of rows.
    In reality the row counts are:
    t1: 20 Million
    t2: 10 Thousand.
    So, I would like to avoid doing DISTINCT and ANALYTIC functions on this large set, so any better way of achiving the same result, with a better statement.
    Thanks.

  • Need help with inner join and distinct rows

    Hey Guys,
    i have
    1) BaseEnv Table 
    2) Link Table
    3) BaseData Table
    Link table has three columns Id,BaseEnvId,BaseDataId 
    the BaseEnvID is unique in the table where as BaseDataId can be repeated i.e multile rows of BaseEnv Table can point to same BaseData  table row
    Now i want to do  BaseEnvTable inner join Link Table inner join BaseData Table and select 5 columsn ; Name,SyncName,Version,PPO,DOM  from the BaseData table.. the problem is that after i do the inner join I get duplciate records..
    i want to eliminate the duplicate records , can any one help me here

    Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Temporal data should
    use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect. 
    This is minimal polite behavior on SQL forums. Now we have to guess and type, guess and type, etc. because of your bad manners. 
    CREATE TABLE Base_Env
    (base_env_id CHAR(10) NOT NULL PRIMARY KEY,
    Think about the name Base_Data; do you have lots of tables without data? Silly, unh? 
    CREATE TABLE Base_Data
    (base_data_id CHAR(10) NOT NULL PRIMARY KEY,
    Your Links table is wrong in concept and implementation. The term “link” refers to a pointer chain structure used in network databases and makes no sense in RDBMS. There is no generic, magic, universal “id” in RDBMS! People that do this are called “id-iots”
    in SQL slang. 
    We can model a particular relationship in a table by referencing the keys in other tables. But we need to know if the relationship is 1:1, 1:m, or n:m. This is the membership of the relationship. Your narrative implies this: 
    CREATE TABLE Links
    (base_env_id CHAR(10) NOT NULL UNIQUE
       REFERENCES Base_Env (base_env_id),
     base_data_id CHAR(10) NOT NULL
       REFERENCES Base_Data (base_data_id));
    >> The base_env_id is unique in the table where as base_data_id can be repeated I.e multiple rows of Base_Env Table can point [sic] to same Base_Data table row. <<
    Again, RDBMS has no pointers! We have referenced an referencing tables. This is a fundamental concept. 
    That narrative you posted has no ON clauses! And the narrative is also wrong. There is no generic “name”, etc. What tables were used in your non-query? Replace the ?? in this skeleton: 
    SELECT ??.something_name, ??.sync_name, ??.something_version, 
           ??.ppo, ??.dom
    FROM Base_Env AS E, Links AS L, Base_Data AS D
    WHERE ?????????;
    >> I want to eliminate the duplicate records [sic], can any one help me here?<<
    Where is the sample data? Where is the results? Please read a book on RDBMS so you can post correct SQL and try again. 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • With clause query with self join

    dear all ,
    i have the following table
    Name                                      Null?    Type
    SURVEY_ID                                 NOT NULL NUMBER(5)
    USER_ID                                   NOT NULL VARCHAR2(15)
    ACADEMIC_SEMESTER                                  VARCHAR2(25)
    USER_TYPE                                          VARCHAR2(7)
    Q1                                            NUMBER(1)
    Q2                                            NUMBER(1)Q1 and Q2 both have five questions 1,2,3,4,5.
    i want to see how much user has slected option 1, how much user select option2 so on and so forth for each question.
    how to do this?
    i write the following query
    with
    Q1_count as (
    select Q1_STAFF,Q13_STAFF,SURVEY_ID,user_id from css_survey
    select count(c.user_id) total_users ,q.Q1_STAFF,q.Q13_STAFF
    from css_survey c,q1_count q
    where c.survey_id=q.SURVEY_ID and c.user_id=q.user_id
    group by q.Q1_STAFF,q.Q13_STAFF
    which generates the following results
    TOTAL_USERS     Q1         Q2
              1              2               5
              1              5               5instead i need the below results;
    TOTAL_USERS     Q1         Q2
              1              2              
              1              5              
              1                            5
              1                            5kindly help.

    okay,
    below is the detail;
    create table css_survey(survey_id number primary key,
    user_id varchar2(30),user_type varchar2(10),academic_semester varchar2(30),
    q1 number,q2 number);
    insert into css_survey values(1,'et04','staff','2010',1,3);
    insert into css_survey values(2,'et03','staff','2010',1,4);
    insert into css_survey values(3,'et05','staff','2010',2,3);
    insert into css_survey values(4,'et06','staff','2010',4,4);
    insert into css_survey values(5,'et07','staff','2010',4,4);
    insert into css_survey values(6,'et08','staff','2010',5,5);
    commit;
    select count(user_id) as total_users,q1,q2
    from css_survey
    group by grouping sets(q1,q2);
    TOTAL_USERS         Q1         Q2
              2                  1
              1                  2
              2                  4
              1                  5
              3                                  4
              1                                  5
              2                                  3
    7 rows selected.and ofcourse this is my desired result.
    thank you so much.

Maybe you are looking for