join query help

Hello everyone, I kindly need help with a query that I'm writing. I think it's supposed to be some kind of join, but I'm a little uncertain. Here is an example:

Select a.person_id, a.company, b.name, e.element, f.value
of a, b, e, f
where a.person_id = b.person_id
and e.el_id = f.el_id
-e.t.c

Lets say this returns

person_id, company, name, element value
------------------------------------------------------
1 vol., krog, breakfast, 34
2, mols, flog, munch, 24

The problem is now the table e. I want to get all the e table values that meet certain criteria. As in:

Select e.element
where e.name = "RATED."

Lets say this returns

element
-----------
food
lunch
Munch

And combine it with the query at the top of the page. But I also want to show all the other values, a.person_id, a.company, b.name for each line.
So my goal is to finally have:

person_id, company, name, element value
------------------------------------------------------
1 vol., krog, breakfast, 34
1 vol., krog, food, 0
1 vol., krog, munch, 0
2, mols, flog, munch, 24
2, mols, flog, food, 0
2, mols, flog, 0

It's to have a default value of zero, where no join does exist for the value and do not duplicate anything even if I could always use separate.
Can anyone help with this?
with t1 as (
            select a.person_id, a.company, b.name, e.element, f.value
              from a, b, e, f
              where a.person_id = b.person_id
              and e.el_id = f.el_id
              -- e.t.c
           ),
     t2 as (
            select e.element
             where e.name = 'EVALUE'
           )
select  person_id,
        company,
        name,
        t2.element,
        sum(
            case t1.element
              when t2.element then value
              else 0
            end
           ) value
  from  t1,
        t2
  group by person_id,
           company,
           name,
  order by person_id,
           company,
           name,
           t2.element
/

For example:

with t1 as (
            select 1 person_id, 'Vols' company, 'krog' name, 'lunch' element, 34 value from dual union all
            select 2, 'Mols', 'flog', 'munch', 24 from dual
           ),
     t2 as (
            select 'food' element from dual union all
            select 'lunch' from dual union all
            select 'munch' from dual
           )
select  person_id,
        company,
        name,
        t2.element,
        sum(
            case t1.element
              when t2.element then value
              else 0
            end
           ) value
  from  t1,
        t2
  group by person_id,
           company,
           name,
           t2.element
  order by person_id,
           company,
           name,
           t2.element
/

 PERSON_ID COMP NAME ELEME      VALUE
---------- ---- ---- ----- ----------
         1 Vols krog food           0
         1 Vols krog lunch         34
         1 Vols krog munch          0
         2 Mols flog food           0
         2 Mols flog lunch          0
         2 Mols flog munch         24

6 rows selected.

SQL> 

SY.

Tags: Database

Similar Questions

  • The self-join query help

    Hello people,
    I have the MENU table on 9i with the following fields:

    MENU_ID, PARENT_ID, NOMMENU...

    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 II TEST
    88889163,6, MAIL
    61.6, SMS
    ...
    ...
    ...

    Thus PARENT_ID shows in which menu the submenu is.

    I need to create the sub report:
    ROOT
    * NETWORK
    * THE CONFIG
    * TEST
    * TEST II
    * SERVICES
    * MAIL
    * SMS
    * CUSTOMERS

    Stars or any other way to identify the depth level will be very handful.

    Thank you in advance.

    Hello

    Try to connect with this example on the emp table.

    select empno,ename,level,sys_connect_by_path(ename,'/') as path
    from emp
    start with mgr is null
    connect by prior empno=mgr
    

    Output
    ------------

    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 
    

    It may be useful
    CKLP

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
    
  • The join SQL query help

    I'm just having a bit of troubel get a correct join query - I thought it was an Inner Join, but I don't get the results I expect.

    My table structure is:

    Table: lodges

    LodgeID (PK)

    Lodge

    etc.

    Table: implemented application

    NominationID (PK)

    Category

    LodgeID

    Year

    So I try to use this structure to replicate this page:

    http://www.safariawards.com/nominees12/

    That is to say a list of boxes for each category, they are appointed on.

    The query I've tried looks like this:

    SELECT appointments. LodgeID, lodges. Lodge, applications. NominationID, applications. Lodges INNER JOIN applications category IT lodges. LodgeID = nominated. NominationID WHERE category = "Best property of Safari in southern Africa" ORDER BY Lodge

    But this product:

    http://www.safariawards.com/nominees12/southernafrica.php

    Its the right number of results, but not the list on the right of the boxes - for example British Airwways is not LodgeID 786

    If anyone could help with the SQL right for what would be well appreciated.

    That you join on the wrong column. Try this:

    SELECT appointments. LodgeID, lodges. Lodge, applications. NominationID, applications. Lodges INNER JOIN applications category IT lodges. LodgeID = nominated. LodgeID WHERE category = "Best property of Safari in southern Africa" ORDER BY Lodge

  • Need help for a join query

    Hi, I'm a little stuck on getting the results of a join query. Let's say I have three tables that make up one of many to go from left to right:
    Project-> work-> work
    Each task can have many tasks. Each task in a job can be repeated by several users, each with a different assigned_name. The tasks of a job have a value of sequence (seq), so if the same task is repeated for a job, the seq will be different.
    I need to get the assigned_name of the last run of the task for each job. Here is the ddl:
    CREATE TABLE project (
    id          NUMBER PRIMARY KEY,
    name     VARCHAR2(20));
    
    INSERT INTO project (id, name) VALUES (1, 'Test Project 1');
    INSERT INTO project (id, name) VALUES (2, 'Test Project 2');
    
    CREATE TABLE job (
    id          NUMBER PRIMARY KEY,
    project_id NUMBER,
    name     VARCHAR2(20),
    CONSTRAINT fk_project 
       FOREIGN KEY (project_id) 
       REFERENCES project(id));
    
    INSERT INTO job (id, project_id, name) VALUES (11, 1, 'Test Job 1-11');
    INSERT INTO job (id, project_id, name) VALUES (12, 1, 'Test Job 1-12');
    INSERT INTO job (id, project_id, name) VALUES (13, 2, 'Test Job 2-13');
    INSERT INTO job (id, project_id, name) VALUES (14, 2, 'Test Job 2-14');
    INSERT INTO job (id, project_id, name) VALUES (15, 2, 'Test Job 2-15');
    
    CREATE TABLE task (
    id          NUMBER,
    seq NUMBER,
    job_id NUMBER,
    name     VARCHAR2(20),
    assigned_name          VARCHAR2(20),
    CONSTRAINT pk_task
       PRIMARY KEY (id, seq),
    CONSTRAINT fk_job
       FOREIGN KEY (job_id) 
       REFERENCES job(id));
    
    INSERT INTO task (id, seq, job_id, name, assigned_name) 
    VALUES (101, 1, 11, 'Test Task 1-11-101', 'Bob');
    INSERT INTO task (id, seq, job_id, name, assigned_name) 
    VALUES (102, 2, 11, 'Test Task 1-11-102', 'Jack');
    INSERT INTO task (id, seq, job_id, name, assigned_name) 
    VALUES (103, 1, 12, 'Test Task 1-12-103', 'Mary');
    INSERT INTO task (id, seq, job_id, name, assigned_name) 
    VALUES (104, 2, 12, 'Test Task 1-12-104', 'Phil');
    INSERT INTO task (id, seq, job_id, name, assigned_name) 
    VALUES (104, 3, 12, 'Test Task 1-12-104', 'Bill');
    INSERT INTO task (id, seq, job_id, name, assigned_name) 
    VALUES (105, 4, 12, 'Test Task 1-12-105', 'Ed');
    INSERT INTO task (id, seq, job_id, name, assigned_name) 
    VALUES (105, 5, 12, 'Test Task 1-12-105', 'Tom');
    INSERT INTO task (id, seq, job_id, name, assigned_name) 
    VALUES (105, 6, 12, 'Test Task 1-12-105', 'John');
    COMMIT;
    Now, if I run a query
    SELECT p.name project_name, j.name job_name, t.name task_name, t.seq, t.assigned_name
    FROM     project p, job j, task t
    WHERE p.id = j.project_id
    AND     j.id = t.job_id
    AND     t.job_id = 12
    ORDER BY 1,2,3,4;
    Then, I get:
    PROJECT_NAME         JOB_NAME             TASK_NAME                   SEQ ASSIGNED_NAME
    -------------------- -------------------- -------------------- ---------- --------------
    Test Project 1       Test Job 1-12        Test Task 1-12-103            1 Mary
    Test Project 1       Test Job 1-12        Test Task 1-12-104            2 Phil
    Test Project 1       Test Job 1-12        Test Task 1-12-104            3 Bill
    Test Project 1       Test Job 1-12        Test Task 1-12-105            4 Ed
    Test Project 1       Test Job 1-12        Test Task 1-12-105            5 Tom
    Test Project 1       Test Job 1-12        Test Task 1-12-105            6 John
    While I would like to:
    PROJECT_NAME         JOB_NAME             TASK_NAME                   SEQ ASSIGNED_NAME
    -------------------- -------------------- -------------------- ---------- --------------------
    Test Project 1       Test Job 1-12        Test Task 1-12-103            1 Mary
    Test Project 1       Test Job 1-12        Test Task 1-12-104            3 Bill
    Test Project 1       Test Job 1-12        Test Task 1-12-105            6 John
    i.e.
    For each combination of project.id/job.id/task.id, I need to get the record with the highest task.seq

    Any ideas? I'm puzzled.

    Thank you.

    I'm on 10g
    SQL> SELECT p.name project_name, j.name job_name, t.name task_name,
      2  max(t.seq) seq,
      3  max(t.assigned_name) keep (dense_rank first order by t.seq desc) assigned_name
      4  FROM project p, job j, task t
      5  WHERE p.id = j.project_id
      6  AND j.id = t.job_id
      7  AND t.job_id = 12
      8  GROUP BY p.name, j.name, t.name
      9  ORDER BY 1,2,3,4
     10  /
    
    PROJECT_NAME         JOB_NAME             TASK_NAME                   SEQ ASSIGNED_NAME
    -------------------- -------------------- -------------------- ---------- --------------------
    Test Project 1       Test Job 1-12        Test Task 1-12-103            1 Mary
    Test Project 1       Test Job 1-12        Test Task 1-12-104            3 Bill
    Test Project 1       Test Job 1-12        Test Task 1-12-105            6 John
    
    SQL> 
    

    SY.

  • Join query not received from WLC

    Hi all

    I am in the process of autonomous update 1242 (MIC) APs belongs to an external client to make them a part of the existing lwapp based infrastructure.

    I have seen successful negotiations of discovery. Then AP sends the join query, but the WLC debugging does not receive the product.

    1. the capture of wireshark packages indicates that Discovery & jOin process use identical to each phased ports: it will be exclude firewalls.

    2. no duplicate IPs

    3 controllers are not exhausted with APs

    4 DHCP option 43 is set up and could see it in action when I do a debug dhcp

    Another interesting observation is that I couldn't see any CERT on autonomous before conveting to lwapp APs when I have HS crypto pki certificates

    Please refer to the attachment for debugging output.

    Any help is very appreciated.

    see you soon,

    janesha

    You open the FW for UDP 12223 and also you have the ip helper and the ip Protocol before?

  • MV incremental update on remote database table join query

    Hello

    I am creating a MV with incremental refresh option on a join query with 2 tables of database remote.

    Created journals of MV on 2 tables in the remote database.
    DROP MATERIALIZED VIEW LOG ON emp;
    CREATE MATERIALIZED VIEW LOG ON emp WITH ROWID;
    DROP MATERIALIZED VIEW LOG ON dept;
    CREATE MATERIALIZED VIEW LOG ON WITH ROWID dept;

    Now, try to create the MV,

    Mv_emp_dept CREATE MATERIALIZED VIEW
    IMMEDIATE CONSTRUCTION
    REFRESH QUICKLY
    START BY SYSDATE
    1 /(24*15) NEXT SYSDATE+.
    WITH THE PRIMARY KEY
    AS
    SELECT e.ename, e.job, d.dname FROM emp@remote_db e, dept@remote_db d
    WHERE e.deptno = d.deptno
    AND e.sal > 800;

    Get the error ORA-12052.

    Can you please help me.

    Thank you
    Anjan

    Need to include the ROWID in the mview. Should be something like: -.

    CREATE MATERIALIZED VIEW mv_emp_dept
    BUILD IMMEDIATE
    REFRESH FAST
    AS
    SELECT e.rowid rowide, e.ename, e.job, d.rowid rowidd, d.dname
    FROM emp@remote_db e,dept@remote_db d
    WHERE e.deptno=d.deptno
    AND e.sal>800;
    
  • Concatinating join query results

    Hello

    Is it possible to concatenate the value of a particular column that are the result of a join query.

    Employee
    Employee Id | Employee Name
    254         | Employee 01 
    266         | Employee 02 
    654         | Employee 03
    741         | Employee 04
    266         | Employee 05
    877         | Employee 06
    955         | Employee 07
    Project
    Project Id | Project Name 
    1          | Project 01   
    2          | Project 02       
    3          | Project 03               
    Project_Employee
    Project Id | Employee ID 
    1          | 254         
    1          | 266        
    1          | 654        
    2          | 741        
    2          | 266        
    3          | 877          
    2          | 955        
    Result
    Project Id | Project Name | Employees
    1          | Project 01   | Employee 01,  Employee 02,  Employee 03
    2          | Project 02   | Employee 04, Employee 05, Employee 07
    3          | Project 03   | Employee 06         
    I use oracle 10g

    Thank you

    Hello

    SQL> with employee as (
      2  select 254 employee_id, 'Employee 01' employee_name from dual  union all
      3  select 266, 'Employee 02' from dual  union all
      4  select 654, 'Employee 03' from dual union all
      5  select 741,  'Employee 04' from dual union all
      6  select 266, 'Employee 05' from dual union all
      7  select 877, 'Employee 06'from dual union all
      8  select  955,         'Employee 07' from dual),
      9  project as (
     10  select  1 project_id,'Project 01' project_name  from  dual union all
     11  select 2 , 'Project 02' from dual  union all
     12  select 3, 'Project 03' from dual),
     13  project_employee as(
     14  select 1 project_id,         254  employee_id from dual union all
     15  select 1 ,         266  from  dual union all
     16  select 1 ,654 from  dual union all
     17  select 2,741  from dual union all
     18  select 2 , 266   from dual  union all
     19  select 3 , 877  from dual union all
     20  select 2 ,955 from dual),
     21  a  as (select  p.project_id, p.project_name, e.employee_id, e.employee_name
    
     22              from employee e, project p, project_employee pe
     23              where pe.project_id = P.project_id
     24              and pe.employee_id = e.employee_id)
     25              select a.project_id proj_id  , a.project_name proj_name,
     26                    rtrim(xmlagg(xmlelement("enam",
     27                                         a.employee_name || ', ')
     28                    order by employee_id).extract('//text()'),', ')
     29                     as employee_names
     30              from a
     31              group by a.project_id,a.project_name;
    
       PROJ_ID PROJ_NAME
    ---------- ----------
    EMPLOYEE_NAMES
    --------------------------------------------------------------------------------
    
             1 Project 01
    Employee 01, Employee 02, Employee 05, Employee 03
    
             2 Project 02
    Employee 02, Employee 05, Employee 04, Employee 07
    
             3 Project 03
    Employee 06
    
    SQL>
    

    The output may be formatted, but the result is what you want.

  • How can I perform this type of beach using DPL join query?

    How can I perform this type of beach using DPL join query?

    SELECT * from t where 1 < = t.a < = 2 and 3 < = t.b. < = 5

    In this pdf file: http://www.oracle.com/technology/products/berkeley-db/pdf/performing%20queries%20in%20oracle%20berkeley%20db%20java%20edition.pdf,

    It shows how to perform "Two motion equal on a single primary database" like SELECT * TAB WHERE A = col1 AND col2 = B using the join entity class, but it does not give a solution on the range join query.

    Right, you can only use an index for this query. If you do not need another index for another query, you might fall (remove @SecondaryKey).

    -mark

  • Help for a LEFT OUTER JOIN query

    Hello, all,.

    I'm having some trouble setting up an Oracle 11 g Server SQL query, and I could use some help.

    Let's say tableA is blogs; tableC is comments for blog entries; tableB is the associative array:

    tableA
    blogID        blogTitle       blogBody      dateEntered
    1             This is a test  More text...  2016-05-20 11:11:11
    2             More testing    Still more!   2016-05-19 10:10:10
    3             Third charm!!   Blah, blah.   2016-05-18 09:09:09
    

    tableC
    commID        userID          userText      dateEntered
    10            Bravo           I like it!    2016-05-20 11:21:31
    11            Charlie         I don't!      2016-05-20 11:31:51
    12            Alpha           Do it again!  2016-05-19 10:20:30
    13            Bravo           Still more?   2016-05-19 10:30:50
    14            Charlie         So, what?     2016-05-19 10:35:45
    15            Bravo           Blah, what?   2016-05-18 09:10:11
    16            Alpha           Magic number! 2016-05-18 09:11:13
    

    tableB
    blogID        commID
    1             10
    1             11
    1             12
    2             13
    2             14
    3             15
    3             16
    
    
    
    

    I'm trying to get blogID, blogTitle, blogBody and the number of comments for each blog entry.  But, since I'm on to_char() for date and COUNT (commID) for the total number of comments, I am not "a group by expression.

    Here is an example of pseudo-SQL of what I'm trying.

    SELECT a.blogID, a.blogTitle, a.blogBody, to_char(a.dateEntered,'YYYY-MM-DD HH24:MI:SS') as dateEntered, COUNT(c.commID) as total
    FROM tableA a LEFT OUTER JOIN tableB b ON b.blog_ID = a.blog_ID
                  LEFT OUTER JOIN tableC c ON c.commID = b.commID
    WHERE a.blogID = '1'
    GROUP BY blogID, blogTitle, blogBody
    ORDER BY to_date(dateEntered,'MM-DD-YYYY HH24:MI:SS') desc
    

    I'm sure it's something simple, but I just DO NOT see it.  Can you help me?

    V/r,

    ^_^

    Try:

    GROUP BY a.blogID, a.blogTitle, a.blogBody, to_char(a.dateEntered,'YYYY-MM-DD HH24:MI:SS')
    

    See you soon

    Eddie

  • need help for an outer join query

    Hi friends...
    I have oracle 10g...
    I have a question which involve is joining three tables...

    the query is as follows:
    SELECT DISTINCT MU.MKT_ID                  "PAR ID",
                       MU.MKT_ID                  "ROOT ID",
                     MSU.SPEC_ID                "ID",
                   SU.SPEC_DESC                "DESC",
               SU.SPEC_CD          "SPEC CD"
    
                  FROM IPOADM_BATCH.MKT_UV1        MU,
                         IPOADM_BATCH.MKT_SPEC_UV1   MSU,
                 IPOADM_BATCH.SPEC_UV1       SU
    
                   WHERE MSU.MKT_ID  = MU.MKT_ID
               AND MSU.SPEC_ID = SU.SPEC_ID
             AND SU.SPEC_GRP_OR_CMPSTN_CD = 'C';
    in my front end application has some delete operations that removes specific data of the IPOADM_BATCH. MKT_SPEC_UV1 due to which the above query is nor fetch all rows.
    the relationship between the tables is clearly from the above query...

    I have the data in IPOADM_BATCH. MKT_UV1 and IPOADM_BATCH. Table of SPEC_UV1 after the delete operation

    now, I want the query above to retrieve data from IPOADM_BATCH. MKT_UV1 with small changes to the above query even if there is no data in IPOADM_BATCH. MKT_SPEC_UV1.

    I thought that if I use an outer join I can get it, but here I have to join three tables-join condition is based on the table that doesn't have a data...


    so please help me guys how can I change the query to get my desired out put...

    Hello

    There are several different things you could mean by it.

    Here's how to join the tables to get one of them:

    SELECT DISTINCT  mu.mkt_id                  "PAR ID",
                     mu.mkt_id                  "ROOT ID",
                     msu.spec_id                "ID",
                     su.spec_desc               "DESC",
                     su.spec_cd                   "SPEC CD"
    FROM           ipoadm_batch.mkt_uv1        mu
    LEFT OUTER JOIN      ipoadm_batch.mkt_spec_uv1   msu  ON   msu.mkt_id               = mu.mkt_id
    LEFT OUTER JOIN  ipoadm_batch.spec_uv1       su       ON   msu.spec_id              = su.spec_id
                                                  AND  su.spec_grp_or_cmpstn_cd = 'C'
    ;
    

    If it does not matter what it is that you want, and then after a small example of data (CREATE TABLE and INSERT, only relevant columns instructions) for all the tables and the results desired from these data.
    Highlight a few places where the above querry is the production of incorrect results of your sample data and explains how to get the correct results in these places.

  • SQL query - help with join

    Dear friends,

    Version of DB - 11.1.0.7... , I'm stuck with SQL basics today... need your help...

    The slot SQL tells me "cache them locks library" in the database that I will put up as a proactive measure.

    I'll be it works via shell script and include the table gv instance_name $ instance ... I'm a little confused as to how a 3rd table "gv$ instance ' can be introduced into the query in order to make the instance_name in the result set...

    SELECT * FROM)

    SELECT / * + LEADING (a) USE_HASH (u) * /.

    instance_name, INST_ID select, blocking_inst_id, blocking_session, username, session_id, sql_id, current_obj #,.

    DECODE (sql_opcode, 1, 'CREATE TABLE', 2, 'INSERT') as "order."

    Event, mod(P1,16) p1, p2, p3

    COUNT (*) totalseconds

    , SUM (CASE WHEN wait_class = 'Application' THEN 1 ELSE 0 END) 'Application '.

    Of

    (SELECT

    a.*

    , TO_CHAR (CASE WHEN session_state = 'WAITING' THEN ELSE null END p1, '0XXXXXXXXXXXXXXX') p1hex

    , TO_CHAR (CASE WHEN session_state = "PENDING" THEN p2 ELSE null END, '0XXXXXXXXXXXXXXX') p2hex

    , TO_CHAR (CASE WHEN session_state = "PENDING" THEN ELSE null END p3, '0XXXXXXXXXXXXXXX') p3hex

    SGS $ active_session_history one) a

    u dba_users

    WHERE

    a.user_id = u.user_id

    AND sample_time BETWEEN sysdate-90 /(24*60) AND sysdate

    - AND a test of ('library cache lock', 'library cache pin")

    AND event like '% library '.

    GROUP BY

    INST_ID select, blocking_inst_id, blocking_session, username, session_id, sql_id, current_obj #,.

    DECODE (sql_opcode, 1, 'CREATE TABLE', 'INSERT', 2),

    event, mod (p1, 16), p2, p3

    Having count (*) > 5

    ORDER BY

    TotalSeconds DESC

    , INST_ID select, blocking_session, username, session_id, sql_id, current_obj #, 'Order', event

    )

    WHERE

    ROWNUM < = 20

    /

    replace

    instance_name

    by

    (select instance_name gv$ instance where INST_ID select = a.inst_id) instance_name

    or select... in... a, u, gv$ instance where... and gv$ instance.inst_id (+) = a.inst_id...

  • Query help - to get the number of employees joined on each month regardless of the year

    Hi all

    I wrote the code below for number of employees joined each month regardless of the year of the employee table. But I couldn't get the result. Kindly help me where I'm wrong in my code,

    Select to_char (hiredate, 'my') as join, count (empno) under the number

    WCP

    To_char Group (hiredate, 'my')

    After having count (empno) > 1;

    Your application displays the list of months (regardless of the year) where more than one employee was engaged with number of emplyees hired this month here. If you want months even if nobody was hired months thast, you emp table outer join to the list of every month:

    with t as)

    Select the level m

    of the double

    connect by level<=>

    )

    Select to_char (to_date (TM, 'mm'), 'my') Lun,

    Count (e.empno) cnt

    t

    left join

    E EMP

    on Tahina = to_char (e.hiredate, 'mm')

    Group of Tahina

    order of Tahina

    /

    MY CNT
    --- ----------
    1 jan
    February 2
    Mar 0
    Apr 2
    May 2
    1 Jun
    July 0
    August 0
    2 sep
    Oct 0
    1 nov

    MY CNT
    --- ----------
    Dec 3

    12 selected lines.

    SQL >

    SY.

  • Need help with a self-join query

    Hello
    I have A table with the following data

    OID parent_oid
    4 of 10
    4 2
    2 2
    12 6
    6 6

    parent_oid is the parent of the oid. I would like a query that displays the final parent of the oid. The result must indicate the following

    Final parent OID
    2 of 10
    4 2
    2 2
    12 6
    6 6

    I use Oracle 10 g. I am familiar with free joins, but that alone will not do the job. Thank you!

    Hello

    arizona9952 wrote:
    ... I am familiar with free joins, but that alone will not do the job.

    You are absolutely right!

    A self-join 2-way would work for lines have no parent, or lines which are directly related to their final ancestor (such as the oid = 4), but not for what anyone further.
    A 3-way self-join would work to a level more away from the last row, but no more. That would be enough with the small set of sample data that you posted, but it won't work if you have added a new rank 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 to 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
    ;
    

    Published by: Frank Kulash, February 22, 2010 19:09

    On sober reflection, I think that a request from top down, as one below, would be more effective than a motion up and down, 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
    ;
    
  • Join SQL query help

    I have two DEVICE and CONTACT tables. The tables are joined for CONTACT_ID DEVICE_ID. I want to print device_ID and the corresponding coordinates on the lower contact. PRIORITY.
    SQL> describe DEVICE;
    DEVICE_ID              NOT NULL VARCHAR2(50)
    
    SQL> describe CONTACT;
    CONTACT_ID               NOT NULL VARCHAR2(50)
    CONTACT_TYPE             NOT NULL VARCHAR2(4)
    PRIORITY                 NOT NULL DOUBLE PRECISION
    LASTNAME                 NOT NULL VARCHAR2(30)
    FIRSTNAME                NOT NULL VARCHAR2(80)
    
    SQL> SELECT a.DEVICE_ID, b.LASTNAME,b.PRIORITY from DEVICE a, CONTACT b where a.DEVICE_ID = 'DEVICEA' and a.DEVICE_ID=b.CONTACT_ID(+);
    DEVICE_ID              LASTNAME    FIRSTNAME PRIORITY CONTACT_TYPE
    ---------------------- ----------- --------- -------- ------------
    DEVICEA                CONTACT1     GN               1 ROUT
    DEVICEA                CONTACT2     Hans             2 ROUT
    How to print a single record with the CONTACT the lowest. PRIORITY?

    Thank you
    Ravi

    rmalghan wrote:
    Thank you Frank, Sundar and Sean. I had less than 3 to work. Two questions. My table of DEVICES has 31936 records.
    1. the first one returned 30207, 31936 records 2nd and 3rd a 30348. Since the 2nd result resembles what I expected, the 1st and 3rd one seem to miss some records. For troubleshooting, I tried to limit the query to a few devices, but do not understand why the difference. Any suggestions?

    The 2nd query not check for type_contact = 'ROUT', it is not surprising that it returns more rows.
    The request of 3rd fact actually an inner join. The "WHERE c.rnum = 1" condition is applied after the join, so he rejects all rows that have been added due to the outer join (which is where all the columns of c are NULL). You probably meant to say:

    LEFT OUTER JOIN got_rnum c ON  d.DEVICE_ID     = c.CONTACT_ID
                               AND c.rnum          = 1; 
    

    without a WHERE clause.

    2. are there advantages in terms of efficiency. 2nd one does not seem to run faster, so I think it's the best. Any comments?

    SELECT a.DEVICE_ID, b.LASTNAME,b.FIRSTNAME,b.PRIORITY
    FROM DEVICE a, CONTACT b
    where
    a.DEVICE_ID=b.CONTACT_ID(+) and
    b.CONTACT_TYPE = 'ROUT' and
    b.PRIORITY = (select min(b1.PRIORITY ) from CONTACT b1 where b1.CONTACT_ID = b.CONTACT_ID);
    
    30207 rows selected (10.12 seconds)
    
    SELECT DEVICE_ID, LASTNAME, PRIORITY
    FROM (
    SELECT a.DEVICE_ID, b.LASTNAME, b.PRIORITY, ROW_NUMBER() OVER (PARTITION BY a.DEVICE_ID ORDER BY b.PRIORITY) row_num
    from DEVICE a, CONTACT b
    where a.DEVICE_ID=b.CONTACT_ID(+))
    WHERE row_num = 1;
    
    31936 rows selected (6.68 seconds)
    
    WITH got_rnum AS (
    SELECT LASTNAME, FIRSTNAME, PRIORITY, CONTACT_TYPE, CONTACT_ID,
    ROW_NUMBER () OVER ( PARTITION BY  CONTACT_ID ORDER BY priority) AS rnum
    FROM contact
    where CONTACT_TYPE = 'ROUT'
    )
    
    SELECT d.DEVICE_ID, c.LASTNAME, c.FIRSTNAME, c.PRIORITY
    FROM device d
    JOIN got_rnum c ON d.DEVICE_ID     = c.CONTACT_ID(+)
    WHERE c.rnum = 1; 
    
    30348 rows selected (9.07 seconds)
    

    This calendar is not very accurate. One that you run first is likely to be slower, because the data are less likely to be stored in the memory cache.

    The 2nd query has only 3 columns in the result set. Which probably doesn't change the speed a lot, but you should fix it anyway.

  • Helps the join query Multiple

    I have three paintings, photos, reviews and prices. Their structures (for short) are as follows:

    photos
    ---------------------
    photoID
    photoTitle

    price
    ---------------------
    priceID
    priceValue
    photoID_fk

    Comments
    ----------------------
    IDCommentaire
    commentText
    photoID_fk

    What I need to do, is to be able to display a list of photos with their price and their comments, autocorrelation, as follows:

    Photo 1
    Price 1
    Price 2
    Comment 1
    Comment 2

    Photo 2
    Price 1
    Price 2

    Photo 3
    Price 1
    Price 2
    Comment 1

    Note that while each photo will always have the same number of values of 'price', some might have comments and some could not.

    I will list the code I have so far, but let me briefly explain what is happening. With the installation I currently, photos in the right order with their values at good price and display comments (if any). Unfortunately, on WITH those comments, the price list of duplicates to match the number of comments returned. So, if Photo 1 has two comments, it will return '1 2 1 2 price price price' for the release of the Awards section.

    I've been pulling my hair over this, and any help that anyone can provide would be greatly appreciated and will potentially save my life.


    Dan-

    Thanks, as always, for your response. Your solution solved the problem!

    As for my database needs, comments are only pictures.

    Basically I have a table that contains all the information about the photos in a gallery. I have another table that holds all the comments that users make on photos. Finally, each photo has 8 sizes (all the same) for sale. So, I don't think that the MTM relationship is there.

    Initially, I was just going to put Size1, Size2, etc. in the pictures 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 each photo has been given 'x' number of entries in the price table, where 'x' is the number of categories of total price (currently 8).

    I don't want to monopolize more time, but if you have a second, I'd be interested to hear an expanded explanation of the restructuring that you proposed at the end of your last response. If you have no time, of course I understand.

    Thanks for your help on this 1 million!

Maybe you are looking for