Self join sub query help

This is my table
Doctor     Appointment Date     Rating
111     23/12/2009     G1
111     23/12/2009     G2
111     23/12/2009     B
111          23/12/2009 D
111     23/12/2008     G1
111          23/12/2008 B
111     23/12/2007     G2
111          23/12/2007 B
111     23/12/2006     D
For Doctor 111, on a given appointment date he has multiple ratings.
I have to fetch the rows (with doctor id, appointment date)
I) which does not have G1 rating but has G2 rating for each appointment date
And vice versa ( does not have G2 rating but has G1 rating for each appointment date)
And
II) if the particular appointment date has both G1 and G2 rating then I can ignore that appointment date – i.e do not fetch any rows if that appointment date has both G1 and G2 ratings.
And
III)     if the appointment date has no G1 or G2 rating, then display the appointment date and the doctor.
So, my result set should have the output from all the three conditions for each doctor.
I am not sure how it works. I am trying using correlated subqueries any suggestions???

ME_XE?with data as
  2  (
  3     select 111 as doc_id, to_date('23/12/2009', 'dd/mm/yyyy') as app_date, 'G1'   as app_type from dual union all
  4     select 111 as doc_id, to_date('23/12/2009', 'dd/mm/yyyy') as app_date, 'G2'   as app_type from dual union all
  5     select 111 as doc_id, to_date('23/12/2009', 'dd/mm/yyyy') as app_date, 'B'    as app_type from dual union all
  6     select 111 as doc_id, to_date('23/12/2009', 'dd/mm/yyyy') as app_date, 'D'    as app_type from dual union all
  7     select 111 as doc_id, to_date('23/12/2008', 'dd/mm/yyyy') as app_date, 'G1'   as app_type from dual union all
  8     select 111 as doc_id, to_date('23/12/2008', 'dd/mm/yyyy') as app_date, 'B'    as app_type from dual union all
  9     select 111 as doc_id, to_date('23/12/2007', 'dd/mm/yyyy') as app_date, 'G2'   as app_type from dual union all
10     select 111 as doc_id, to_date('23/12/2007', 'dd/mm/yyyy') as app_date, 'B'    as app_type from dual union all
11     select 111 as doc_id, to_date('23/12/2006', 'dd/mm/yyyy') as app_date, 'D'    as app_type from dual
12  )
13  select
14     doc_id,
15     app_date,
16     app_type
17  from
18  (
19     select
20        sum( case when app_type = 'G1' then 1 else 0 end ) over (partition by doc_id, app_date) as g1,
21        sum( case when app_type = 'G2' then 1 else 0 end ) over (partition by doc_id, app_date) as g2,
22        doc_id,
23        app_date,
24        app_type
25     from data
26  )
27  where g1 = 0 and g2 = 0
28  or
29  (
30     g1 > 0 and g2 = 0
31  )
32  or
33  (
34     g2 > 0 and g1 = 0
35  );
            DOC_ID APP_DATE                   APP_TY
               111 23-DEC-2006 12 00:00       D
               111 23-DEC-2007 12 00:00       B
               111 23-DEC-2007 12 00:00       G2
               111 23-DEC-2008 12 00:00       G1
               111 23-DEC-2008 12 00:00       B
5 rows selected.
Elapsed: 00:00:00.59
ME_XE?
ME_XE?select * from v$version;
BANNER
Oracle Database 10g Express Edition Release 10.2.0.1.0 - Product
PL/SQL Release 10.2.0.1.0 - Production
CORE    10.2.0.1.0      Production
TNS for Linux: Version 10.2.0.1.0 - Production
NLSRTL Version 10.2.0.1.0 - Production
5 rows selected.
Elapsed: 00:00:00.64Is one method using analytics (which allow you to perform operations over a 'window' of data, which seems to be what you need to do).

Similar Messages

  • How to do an INNER JOIN sub-query?

    Can't seem to find anything that would help me out with this.
    My prototype query goes like this but its giving me a ORA-00905: missing keyword
    SELECT Poker_Site.site_name, bonus.sign_up_bonus
         FROM poker_site
         INNER JOIN bonus
         WHERE Poker_site.site_name = 'Poker Stars'
         ON Poker_Site.site_name = bonus.site_name;

    INNER JOIN join must be immediately followed by ON and only then by WHERE:
    SELECT Poker_Site.site_name, bonus.sign_up_bonus
    FROM poker_site
    INNER JOIN bonus
    ON Poker_Site.site_name = bonus.site_name
    WHERE Poker_site.site_name = 'Poker Stars';SY.

  • Sub Query Help

    First, I'm new to oracle so please bear with me....
    I have the current query which works great:
    SELECT
    CASE WHEN (RX.STORENBR = '101114') THEN 'CC-FTL'
    WHEN (RX.STORENBR = '103073') THEN 'CC-MIA'
    WHEN (RX.STORENBR = '102520') THEN 'CC-WPB'
    ELSE '0'
    END AS PHARMACY_NAME,
    CASE WHEN (RX.STORENBR = '101114') THEN '1598762015'
    WHEN (RX.STORENBR = '103073') THEN '1063423606'
    WHEN (RX.STORENBR = '102520') THEN '1770580292'
    ELSE '0'
    END AS PHARMACY_NPI,
    CASE WHEN (RX.STORENBR = '101114') THEN '1079638'
    WHEN (RX.STORENBR = '103073') THEN '1019303'
    WHEN (RX.STORENBR = '102520') THEN '1099286'
    ELSE '0'
    END AS PHARMACY_NCPDP,
    CASE WHEN (RX.STORENBR = '101114') THEN 'BN9568861'
    WHEN (RX.STORENBR = '103073') THEN 'BN9754450'
    WHEN (RX.STORENBR = '102520') THEN 'BA8399962'
    ELSE '0'
    END AS PHARMACY_DEA,
    PATIENT.PATSTOREID AS PT_STORE,
    PATIENT.PATKEY AS PT_KEY,
    (PATIENT.PATSTOREID || LPAD(PATIENT.PATKEY, 6, 0)) AS PTID,
    DOCTOR.NAMELAST AS PRESCRIBER_LAST,
    DOCTOR.NAMEFIRST AS PRESCRIBER_FIRST,
    DOCTOR.ADRSCITY AS PRESCRIBER_CITY,
    DOCTOR.ADRSSTATE AS PRESCRIBER_STATE,
    DOCTOR.ADRSZIP AS PRESCRIBER_ZIP,
    DOCTOR.STATENUMBER,
    DOCTOR.DEAALPHAALPHA || DOCTOR.DEAALPHANBR || DOCTOR.DEAALPHASFX AS PRESCRIBER_DEA,
    CASE WHEN (DOCTOR.PLANCODE01 = 'NPI') THEN DOCTOR.PLANID01
    WHEN (DOCTOR.PLANCODE02 = 'NPI') THEN DOCTOR.PLANID02
    WHEN (DOCTOR.PLANCODE03 = 'NPI') THEN DOCTOR.PLANID03
    ELSE '0'
    END AS NPI,
    DOCTOR.SPECIALTY,
    DRUG.NAME, DRUG.DRUGNDCNBR,
    PLANS.PLANID,
    (NVL(RX.CASHPAID, 0)/100) AS COPAY,
    to_char(to_date(RX.FILLDATE, 'yyyyddd'), 'MM/DD/YYYY') AS DISPENSED_DATE,
    RX.DISPENSEDQTY01, RX.DAYSUPP,
    FROM RX
    LEFT OUTER JOIN PLANS ON (RX.PLANSTOREID01=PLANS.PLANCODESTOREID AND RX.PLANKEY01=PLANS.PLANCODEKEY)
    LEFT OUTER JOIN DRUG ON (RX.DISPENSEDDRUGSTOREID=DRUG.DRUGNBRSTOREID AND RX.DISPENSEDDRUGKEY=DRUG.DRUGNBRKEY)
    LEFT OUTER JOIN DOCTOR ON (RX.DOCNBRSTOREID=DOCTOR.DOCSTOREID AND RX.DOCNBRKEY = DOCTOR.DOCKEY)
    LEFT OUTER JOIN PATIENT ON (RX.PATNBRSTOREID=PATIENT.PATSTOREID AND RX.PATNBRKEY=PATIENT.PATKEY)
    WHERE RX.FILLDATE >= 2007274
    AND RX.FILLDATE <= 2007304
    AND DRUG.DRUGNDCNBR = 0004038039
    AND NVL(RX.RXSTATUS, 0) <> 16
    AND NVL(RX.RXSTATUS, 0) <> 17
    AND NVL(RX.RXSTATUS, 0) <> 18
    AND NVL(RX.RXSTATUS, 0) <> 20
    AND NVL(RX.RXSTATUS, 0) <> 24
    AND NVL(RX.RXSTATUS, 0) <> 32
    AND NVL(RX.RXSTATUS, 0) <> 33
    AND NVL(RX.RXSTATUS, 0) <> 48
    However, I also want to add a subquery to return the LEAST(RX.FILLDATE) on each Patient.Patkey. I belive the subquery should be something like this:
    SELECT * FROM (
    SELECT RX.FILLDATE AS FIRST_DATE
    FROM RX
    LEFT OUTER JOIN DRUG ON (RX.DISPENSEDDRUGSTOREID=DRUG.DRUGNBRSTOREID AND RX.DISPENSEDDRUGKEY=DRUG.DRUGNBRKEY)
    WHERE RX.PATNBRSTOREID=PT_STORE
    AND RX.PATNBRKEY=PT_KEY
    AND DRUG.DRUGNDCNBR = 0004038039
    ORDER BY LEAST(RX.FILLDATE)
    WHERE ROWNUM = 1
    How do I format the subquery so oracle performs the lookup on each record returned in the main query, based on the main query's "WHERE" Clause?

    Don't know if your version supports subquery factoring this way the whole thing is much more evident
    with
    the_query as
    < your query here >
    the_subquery as
    < your subquery here >
    select the_query.*,the_subquery.*
      from the_query
      left outer join the_subquery on (< join conditions here >)or (in old notation)
    select q.*,s.*
      from (< your query here >) q,
           (< your subquery here >) s,
    where < join conditions here > Regards
    Etbin

  • SQL Sub-Query Help

    Hi,
    1. In the query below, How to display FirstActNum to the User( which is inner select decode statement ) ?
    SELECT A.One, A.Two, A.Three, A.Four from
    (Select FL.first_act_num as One,FL.move_num as Two, SUM (FL.payment) as Three,SUM(FL.next_amount) as Four from FirstLib FL
    where FL.act_num IN (
    Select
    DECODE(l.first_act_num,'0000000',l.act_num,l.first_act_num) as FirstActNum
    from FirstLib L, ManageAccount A
    WHERE
    L.act_id=A.act_id
    AND A.id='123456789')
    group by FL.primary_acct_num,FL.loan_num) A,OtherTable B
    where A.One = B.first_act_num AND A.Two = B.move_num;
    2. Is there any other better way to write these kind of queries?
    Thanks

    Sundar,
    No, its different.. I am just comparing with that field.
    The data looks like..
    ACT_NUM      FIRST_ACT_NUM
    11111          11111
    22222          11111
    33333          11111
    In some cases FIRST_ACT_NUM is not populated (i.e it will have 0000000), in this case I am using ACT_NUM
    ACT_NUM      FIRST_ACT_NUMM
    55555          0000000
    87878          0000000
    90909          0000000

  • Hi! Everyone, I have some problems with JOIN and Sub-query; Could you help me, Please?

    Dear Sir/Madam
    I'm a student who is interested in Oracle Database and
    I have some problems with JOIN and Sub-query.
    I hope so many of you could help me.
    if i use JOIN without sub-query, may it be faster or not?
    SELECT field1, field2 FROM tableA INNER JOIN tableB
    if i use JOIN with sub-query, may it be faster or not?
    SELECT field1,field2,field3 FROM tableA INNER JOIN (SELECT field1,field2 FROM tableB)
    Thanks in advance!

    Hi,
    fac30d8e-74d3-42aa-b643-e30a3780e00f wrote:
    Dear Sir/Madam
    I'm a student who is interested in Oracle Database and
    I have some problems with JOIN and Sub-query.
    I hope so many of you could help me.
    if i use JOIN without sub-query, may it be faster or not?
    SELECT field1, field2 FROM tableA INNER JOIN tableB
    if i use JOIN with sub-query, may it be faster or not?
    SELECT field1,field2,field3 FROM tableA INNER JOIN (SELECT field1,field2 FROM tableB)
    Thanks in advance!
    As the others have said, the execution plan will give you a better idea about which is faster.
    If you're trying to see how using (or not using) a sub-query affects performance, make the rest of the queries as similar as possible.  For example, include field3 in both queries, or ignore field3 in both queries.
    In this particular case, I guess the optimizer would do the same thing either way, but that's just a guess.  I can't see your execution plans.
    In general, simpler code is faster, and better in other ways, too.  In this case
    tableB
    is simpler than
    (SELECT field1, field2  FROM tableB)
    Why do you want a sub-query in this example?

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

  • Self Joining and Inline Query. A tricky report.

    I am stuck with a very tricky situation.Please help.This is PROD issue.
    I have written a SQL code which has 1 inline queries,and displays the right results
    with the right report output
    Dont get confused.Just go thru this.
    select   pie.id_inst_code,
             ISNULL(PN.Active, 0)                 'Active',
    from position_master_input_event pie,
    (select  insx.id_inst_xref_type,insx.id_inst_xref,count(*) 'PrimaryListing'
    from instrument ins, instrument_xref insx
    where ins.id_inst = insx.id_inst
    and   insx.flg_active = 'Y'
    and   ins.flg_active  = 'Y'
    group by insx.id_inst_xref_type,insx.id_inst_xref
    )PN
    where     id_entity = 'AGL'
    and       pie.id_inst_code *= PN.id_inst_xref
    and       pie.id_src_inst_code_type*= PN.id_inst_xref_type
    group by  pie.id_inst_code,PN.Active,
    Table :Instrument_xref
    id_inst      id_inst_xref_type    id_inst_xref  flg_active
    0372285      SE                   B0DV8Y9       Y
    0372285      IS                   GB00B03MLX29  Y
    Table :Instrument
    id_inst      id_inst_xref_type    id_inst_xref  flg_active  flg_primary_listing
    0372285      SE                   B0DV8Y9       Y           N 
    OUTPUT:
    id_inst_xref                      Active
    B0DV8Y9                           1
    PERFECT.Works fine
    2) Now comes the tricky part.:
        0372285 also has GB00B03MLX29 which has flg_active to Y and which also maps to 0372285.
        Am I right?
        New reportOutput
        id_inst_xref                      Active   PRIMARY ISIN
        B0DV8Y9                           1        1
        So,now I want a SELF JOIN this way built into the code:
        (hardcoded values work)
        (i)
        select  a.id_inst_xref
        from instrument_xref a,
             instrument_xref b
        where b.id_inst_xref ='B0DV8Y9'
        and   b.id_inst = a.id_inst
        and   b.id_inst_xref_type in ('SE','IS')
        and   a.id_inst_xref =  'GB00B03MLX29'
        (ii)
         select count(*) 'PrimaryISIN'
         from instrument ins,
             instrument_xref insx
         where ins.id_inst = insx.id_inst
         and   insx.flg_active = 'Y'
         and   ins.flg_primary_listing = 'Y'
         and   ins.flg_active = 'Y'
         And now LINKING ALL :
        select   pie.id_inst_code,
             ISNULL(PN.Active, 0)                 'Active',
        from position_master_input_event pie,
        (select  insx.id_inst_xref_type,insx.id_inst_xref,count(*) 'PrimaryListing'
         from instrument ins, instrument_xref insx
         where ins.id_inst = insx.id_inst
         and   insx.flg_active = 'Y'
         and   ins.flg_active  = 'Y'
         group by insx.id_inst_xref_type,insx.id_inst_xref
        )PN,
        (select count(*) 'PrimaryISIN'
         from instrument ins,
             instrument_xref insx
         where ins.id_inst = insx.id_inst
         and   insx.flg_active = 'Y'
         and   ins.flg_primary_listing = 'Y'
         and   ins.flg_active = 'Y'
          and     insx.id_inst_xref = ( 
                                           select  DISTINCT  a.id_inst_xref
                                            from    instrument_xref a,
                                            instrument_xref  b
                                      where b.id_inst_xref = 'B0DV8Y9'
                                          and     b.id_inst = a.id_inst
                                          and     b.id_inst_xref_type in ('SE','IS')
                                       and    a.id_inst_xref =  'GB00B03MLX29'
        where     id_entity = 'AGL'
        and       pie.id_inst_code *= PN.id_inst_xref
        and       pie.id_src_inst_code_type*= PN.id_inst_xref_type
        group by  pie.id_inst_code,PN.Active,
        THE Self join works fine as long as it is hardcoded.
        But assume there can br multiple such situations as the above,and I dont want to
        hardcode the values,how can I build the NEW REPORT by SELF JOINING.
        Please can someome help.This is a tricky one.
        Is there a better way to this

    Isn't this the same question as:
    Passing values dynamically Froman 'INLINE Query' to a 'SUB QUERY'
    and
    Another query regarding Inline Query and Self Join and pass Column Values

  • Joining with sub query not working

    Hi
    I am new with these complex queries. I am trying to join a sub query to a query as below;
    SELECT Events1.InvoiceBatch AS BatchNo, Events1.InvoiceBatchDate AS BatchDate, tblClients.Company, tblClients.ID AS ClientID, COUNT(Events1.ID) AS Invoices,
    COUNT(*) - COUNT(Events1.InvoicePrintDate) AS E, Events1.InvoiceBatchFromDate AS BatchFrom, Events1.InvoiceBatchToDate AS BatchTo, (SELECT EventID, SUM(Total) FROM tblStaffBookings AS StaffBookings WHERE StaffBookings.EventID = Events1.ID GROUP BY EventID) AS Total
    FROM tblEvents AS Events1 LEFT OUTER JOIN
    tblClients ON Events1.ClientID = tblClients.ID
    WHERE (Events1.FactoringExportDate IS NULL) OR (Events1.AccountsExportDate IS NULL) OR (Events1.InvoiceSentDate IS NULL)
    GROUP BY Events1.InvoiceBatch, Events1.InvoiceBatchDate, tblClients.Company, tblClients.ID, Events1.InvoiceBatchFromDate, Events1.InvoiceBatchToDate
    HAVING (Events1.InvoiceBatch = 5212)
    ORDER BY tblClients.Company
    I am getting these two errors;
    Msg 8120, Level 16, State 1, Line 2
    Column 'tblEvents.ID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
    Msg 116, Level 16, State 1, Line 2
    Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
    What am I missing?
    Thanks
    Regards

    SELECT Events1.InvoiceBatch AS BatchNo, Events1.InvoiceBatchDate AS BatchDate, tblClients.Company, tblClients.ID AS ClientID, COUNT(Events1.ID) AS Invoices,
    COUNT(*) - COUNT(Events1.InvoicePrintDate) AS E, Events1.InvoiceBatchFromDate AS BatchFrom, Events1.InvoiceBatchToDate AS BatchTo,Total
    FROM tblEvents AS Events1 LEFT OUTER JOIN
    tblClients ON Events1.ClientID = tblClients.ID
    LEFT OUTER JOIN (SELECT EventID, SUM(Total) AS Total FROM tblStaffBookings AS StaffBookings WHERE StaffBookings.EventID = Events1.ID GROUP BY EventID) sb
    ON sb.EventID = Events1.ID
    WHERE (Events1.FactoringExportDate IS NULL) OR (Events1.AccountsExportDate IS NULL) OR (Events1.InvoiceSentDate IS NULL)
    GROUP BY Events1.InvoiceBatch, Events1.InvoiceBatchDate, tblClients.Company, tblClients.ID, Events1.InvoiceBatchFromDate, Events1.InvoiceBatchToDate,Total
    HAVING (Events1.InvoiceBatch = 5212)
    ORDER BY tblClients.Company
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page
    Says;
    Msg 4104, Level 16, State 1, Line 5
    The multi-part identifier "Events1.ID" could not be bound.
    on
    LEFT OUTER JOIN (SELECT EventID, SUM(Total) AS Total FROM tblStaffBookings AS StaffBookings WHERE StaffBookings.EventID = Events1.ID GROUP BY EventID) sb
    Regards

  • How to rewrite this query without sub query please help me

    Hello All Good Evening,
    Could you please help me with this query, how can i write this query without sub query, or how can write this query another ways
    please help me
    select planno, status1, count(*) Counts from
    select a.ValetNO PlanNo  ,
    case 
         when JoinCode in ('00', '01', '02') then 'Actcess'
         when JoinCode in ('20', '21', '22', '23','38', '39') then
         'Secured' else 'Other' end Status1 ---, COUNT (*)
       from  dbo.ppt a(NOLOCK)  left join dbo.acts b on a.P_ID = b.P_ID and a.ValetNO  = b.ValetNO
    --group by a.ValetNO
      a group by planno, status1
    order by 2
    Thank you in Advance
    Milan

    Whats your objective here? Sorry, am not able to understand the reason for this change. 
    Try the below:(Not tested)
    ;With cte
    As
    select a.ValetNO PlanNo ,
    case
    when JoinCode in ('00', '01', '02') then 'Actcess'
    when JoinCode in ('20', '21', '22', '23','38', '39') then
    'Secured' else 'Other' end Status1 ---, COUNT (*)
    from dbo.ppt a(NOLOCK) left join dbo.acts b on a.P_ID = b.P_ID and a.ValetNO = b.ValetNO
    select planno, status1, count(*) Counts from cte
    a group by planno, status1
    order by 2
    Even below:
    select a.ValetNO PlanNo ,
    case
    when JoinCode in ('00', '01', '02') then 'Actcess'
    when JoinCode in ('20', '21', '22', '23','38', '39') then
    'Secured' else 'Other' end Status1 , COUNT (1)
    from dbo.ppt a(NOLOCK) left join dbo.acts b on a.P_ID = b.P_ID and a.ValetNO = b.ValetNO
    Group by a.ValetNO ,
    case
    when JoinCode in ('00', '01', '02') then 'Actcess'
    when JoinCode in ('20', '21', '22', '23','38', '39') then
    'Secured' else 'Other' end

  • Issue with join condition while using in the corelated sub query

    Bees,
    I am not able to use the below query since i have used a join condition in the corelated sub qery inline view.But i have a requirement like this . Please help me on this
    select * from dept d
    where exists (select 1 from (
    select deptno
    from emp where deptno= d.deptno)
    Thank you
    Boooo

    Hi,
    I've never seen a general solution for how to reference columns from main query a from sub-query c, where c is is sub-query of b, which is a sub-query of a.
    Whenever I've wanted to, I've been able to get the desired results with a different approach.
    In this case, you seem to want
    SELECT     *
    FROM     dept     d
    WHERE     EXISTS     (
              SELECT     1
              FROM     emp
              WHERE     deptno     = d.deptno
              );I'm guessing at your data and desired output.

  • Cross-listing Query (Partition By Clause? Self-Join?)

    Hello,
    I need a query that will cross-list courses a professor is teaching this semester. Essentially, two fields need to be the same (i.e.: Section & CourseTitle), while the third field is different (i.e.: Subject).
    For example, Max Power is a professor teaching 3 courses, one is cross-listed (ENG 123 and JRL 123):
    LastName     FirstName     Subject     Section     CourseTitle
    Power          Max          ENG     123     English Composition
    Power          Max          ENG     452     Robert Frost Poetry     
    Power          Max          JRL     123     English Composition
    Power           Max          ENG      300     Faulkner & TwainThe desired query output is this:
    LastName     FirstName     Subject     Section     CourseTitle
    Power          Max          ENG     123     English Composition
    Power          Max          JRL     123     English CompositionBasically, I need only the cross-listed courses in the output.Is this an instance where I use a "Partition By Clause" or should I create a self-join?
    Much thanks for any help and comments.

    Unfortunately, I can't create new tables. I don't have permission. I can't alter, add or delete any of the data.
    So I tried Frank's code with my data:
    WITH got_cnt AS
    SELECT  sivasgn_term_code, spriden_id, spriden_last_name, spriden_first_name,
                    ssbsect_ptrm_code, ssbsect_camp_code,
                    sivasgn_crn, ssbsect_subj_code, ssbsect_crse_numb, scbcrse_title,
           count(*) over (partition by ssbsect_crse_numb, scbcrse_title) cnt
    FROM spriden INNER JOIN sivasgn ON spriden_pidm = sivasgn_pidm JOIN
         ssvsect ON ssbsect_crn = sivasgn_crn JOIN
         sfrstcr ON sfrstcr_crn = sivasgn_crn
    WHERE  ssbsect_term_code= sivasgn_term_code  
    AND sfrstcr_term_code = sivasgn_term_code
    AND ssbsect_enrl > '0' and sivasgn_credit_hr_sess > '0'
    AND sivasgn_term_code IN ('200901', '200909')
    AND spriden_change_ind IS NULL
    AND ssbsect_camp_code IN ('1', '2', 'A', 'B')
    SELECT DISTINCT sivasgn_term_code, spriden_id, spriden_last_name, spriden_first_name,
                    substr(ssbsect_ptrm_code,1,1) as ptrm_code, ssbsect_camp_code,
                    sivasgn_crn, ssbsect_subj_code, ssbsect_crse_numb, scbcrse_title
    FROM got_cnt
    WHERE cnt >1
    ORDER BY spriden_last_name, sivasgn_term_code, ssbsect_crse_numb;The output pretty much displays all courses with same subject code, course number and course title.
    Output:
    LastName     FirstName     Subject     Section     CourseTitle
    Power          Max          ENG     123     English Composition
    Power          Max          ENG     123     English Composition
    Power          Max          ENG     452     Robert Frost Poetry
    Power          Max          ENG     452     Robert Frost Poetry
    Power           Max          ENG      300     Faulkner & Twain
    Power           Max          ENG      300     Faulkner & Twain
    Power          Max          JRL     123     English Composition
    Power          Max          JRL     123     English CompositionWhat I would like is same course number, course title, BUT different subject code. Pretty much that in my first post of this thread.
    Desired Output:
    LastName     FirstName     Subject     Section     CourseTitle
    Power          Max          ENG     123     English Composition
    Power          Max          JRL     123     English CompositionMaybe I'm explaining this wrong. Any help would be greatly appreciated. Thanks.

  • Self join please help

    I would be very grateful if someone would show me show to use the self join, I understand what is does but just don't know how to use it. I have a question from a exercise but no answer so I can't check it the question is - using temporary labels to abbreviate table names, find all the staff that earn more than 'SONG'.
    here is the table
    STAFFID SNAME JOB MGR STARTDATE SAL COMM BRANCHID
    5963 SMITH ADMIN 5209 15-NOV-00 1600 20
    5994 BATES ASSISTANT 5896 20-FEB-01 1800 100 30
    5125 CHAN ASSISTANT 5896 22-FEB-02 1550 150 30
    5665 JONES MANAGER 5938 02-MAR-01 3100 20
    5465 WILSON ASSISTANT 5896 28-OCT-00 1250 140 30
    5896 HAYAT MANAGER 5938 01-MAY-01 3100 30
    5287 CLARK MANAGER 5938 09-JUL-02 3100 10
    5887 COSTA BUYER 5665 18-APR-04 3150 20
    5938 SHAW DIRECTOR 17-NOV-01 7000 10
    5484 TURNER ASSISTANT 5896 08-OCT-01 1550 0 30
    5678 KALIM ADMIN 5887 23-APR-04 1600 20
    5009 JAMES ADMIN 5896 03-DEC-01 1600 30
    5209 SONG BUYER 5665 03-JAN-02 3000 20
    5439 SIMPSON ADMIN 5287 23-FEB-02 1600 10
    Thanks in advanced :)
    Edited by: user11093259 on 01-Dec-2010 10:19

    Hi,
    Welcome to the forum!
    Always post your best attempt at solving the problem. You'll get more specific replies that will help you learn more, and it often clarifies what you're trying to do.
    Here's a typical self-join, using the scott.dept table (which you probably have avaialble).
    SELECT     l.dname          AS lower_dname
    ,     h.dname          AS higher_dname
    FROM     scott.dept     l
    JOIN     scott.dept     h  ON     l.dname     < h.dname
    ;Output:
    LOWER_DNAME    HIGHER_DNAME
    ACCOUNTING     OPERATIONS
    ACCOUNTING     RESEARCH
    ACCOUNTING     SALES
    OPERATIONS     RESEARCH
    OPERATIONS     SALES
    RESEARCH       SALESAs you can see, this pairs every higher_dname with every dname that is less than it.
    This is very similar to your problem. The main difference is, where the query above shows every possible higher_dname (and the lower_dnames related to it), you're interested in a single, specific higher value (and the rolws with lower values related to it). You can restrict the query to show only that one, specific higher values by adding a WHERE clause. Try it. If you get stuck, ask a more specific question, and, remember, post your code.

  • Outter-Join with requirement for sub-query

    I am working on a view that needs to return 1 record per payment date within the primary payment table.
    Part of the information that is to be returned in this row comes from a date-controlled table containing superannuation information. This data may or may not be present, requiring an outer-join. The final problem is that there may be multiple rows in this superannuation table requiring me to retrieve the record with the most recent start date, prior to the payment date. This is where I'm breaking down currently as I cannot outer-join to a sub-query.
    I had an idea that I could create an inline view of the superannuation table with 1 row for each of the last 365 days (The reports that will be built off the view are always run within 1-2 months of the payment date), with the date and either the required information or blanks if it did not exist. This would avoid me requiring an outer-join as I could just join on the payment date to the date in the inline query and return whatever data was there.
    I'm pretty sure I should be able to do this with analytics rather than creating a date table, by restricting the rows to 365, then havign a column that is effectively the previous column - 1. Unfortunately I'm fairly new to analytics and find the Oracle documentation hard to decipher.
    Can anyone help with this or perhaps suggest an alternate solution?

    please don't do that. that's the most pathetic way generate rows. all_objects is a very nasty view, and oracle reserves the right to merge the view into the rest of your query, making performance less than you had hoped for. how about this instead:
    select ...
    from (
    select trunc(sysdate-rownum+1) super_date
    from dual
    connect by level < = 365 ) dates,
    your_table_here
    where dates.super_date = your_column (+)
    ...

  • How to make outer join in Sub Query?

    Hi!
    I'm facing one problem. Can anyone tell me - how to make outer join in sub query?
    I'm pasting one sample code -
    select e.empno, e.ename,e.job,e.sal,d.deptno,d.dname
    from d_emp e, d_dept d
    where e.deptno(+) = (
                          case
                            when d_dept.deptno = 10
                              then
                                  select deptno
                                  from d_dept
                                  where dname = 'SALES'
                          else
                            d_dept.deptno
                          end
    SQL>
    ERROR at line 15:
    ORA-01799: a column may not be outer-joined to a subqueryHow to resolve this issue?
    Regards.

    And any luck with this?
    SQL> with emp as
      2  (select 100 empno, 'Abcd' ename, 1000 sal, 10 deptno from dual
      3  union all
      4  select 101 empno, 'RRR' ename, 2000 sal, 20 deptno from dual
      5  union all
      6  select 102 empno, 'KKK' ename, 3000 sal, 30 deptno from dual
      7  union all
      8  select 103 empno, 'PPP' ename, 4000 sal, 10 deptno from dual
      9  )
    10  ,dept as
    11  (select 10 deptno, 'FINANCE' dname from dual
    12  union all
    13  select 20 deptno, 'SALES' dname from dual
    14  union all
    15  select 30 deptno, 'IT' dname from dual
    16  union all
    17  select 40 deptno, 'HR' dname from dual
    18  )
    19  select e.empno, e.ename, e.sal, d.deptno, d.dname
    20  from emp e,
    21       (select decode(a.deptno, 10, b.deptno, a.deptno) deptno, decode(a.deptno, 10, b.dname, a.dname) dname
    22      from dept a, (select deptno, dname
    23                    from dept
    24                      where dname = 'SALES'
    25                     ) b
    26       ) d
    27  where e.deptno(+) = d.deptno
    28  /
         EMPNO ENAM        SAL     DEPTNO DNAME
           101 RRR        2000         20 SALES
           101 RRR        2000         20 SALES
           102 KKK        3000         30 IT
                                       40 HR
    SQL> Cheers
    Sarma.

  • Correlated sub-query/outer join problem

    Hi,
    I have a problem similar to this one (Outer join with correlated subquery but I'm struggling to find a solution for mine!
    The following query works OK unless there is no entry in room_prices, so I need to outer join somehow to that table otherwise it doesn't return any rows.
    The main difference between the query in the other thread and mine is that mine has an extra table (bookings b) in the sub-query, which is complicating things a bit.
    select b.book_from,
         b.book_to,
         b.flat_rate,
         nvl(c.discount,0),
         p.hourly,
         p.half_day,
         p.daily,
         p.discountable,
         p.surcharge,
         l.evening_start,
         nvl(b.full_day,'N')
    from booking.bookings b,
    booking.customer c,
    booking.room_prices p,
    booking.rooms r,
    booking.location l
    where b.id = 9272
    and c.id = b.customer
    and b.room = p.room
    and b.room = r.id
    and r.loc = l.id
    and p.from_date =
    select max(p2.from_date)
    from booking.room_prices p2
    where p2.room = p.room
    and p2.from_date < b.book_from
    Could anyone suggest a way to re-write the query so that it is outer joined to room_prices?
    Thanks,
    Hazel

    Thanks for both of your responses.
    Unfortunately your suggestion didn't work Dmytro - still no rows are returned.
    Here are some table creation scripts and test data to insert:
    CREATE TABLE BOOKINGS
    ID NUMBER NOT NULL,
    ROOM NUMBER NOT NULL,
    CUSTOMER NUMBER NOT NULL,
    BOOK_FROM DATE NOT NULL,
    BOOK_TO DATE NOT NULL,
    CONFIG VARCHAR2(24) NOT NULL,
    CREATED_DATE DATE NOT NULL,
    CREATED_BY VARCHAR2(16) NOT NULL,
    UPDATED_DATE DATE,
    UPDATED_BY VARCHAR2(16),
    DELEGATES NUMBER,
    NARRATIVE VARCHAR2(256),
    CONTACT_DETAILS VARCHAR2(400),
    CONFIRMED VARCHAR2(1),
    CANC_REASON NUMBER,
    FULL_DAY VARCHAR2(1),
    FLAT_RATE NUMBER,
    STANDBY NUMBER,
    TOTAL_STANDBY_TIME DATE,
    PRE_STANDBY_TIME DATE,
    PRE_STANDBY NUMBER,
    GL_CODE VARCHAR2(20)
    CREATE TABLE CUSTOMER
    ID NUMBER NOT NULL,
    CUSTOMER VARCHAR2(160) NOT NULL,
    CONTACT_ADDRESS VARCHAR2(240),
    CONTACT_TELEPHONE VARCHAR2(20),
    CONTACT_EMAIL VARCHAR2(160),
    CREATED_DATE DATE NOT NULL,
    CREATED_BY VARCHAR2(16) NOT NULL,
    UPDATED_DATE DATE,
    UPDATED_BY VARCHAR2(16),
    DISCOUNT NUMBER(5,2),
    CUST_TYPE VARCHAR2(1),
    CONTACT_FAX VARCHAR2(20),
    DEBTOR_NO VARCHAR2(20),
    BC_CONTACT VARCHAR2(64)
    CREATE TABLE ROOMS
    ID NUMBER NOT NULL,
    LOC NUMBER NOT NULL,
    NAME VARCHAR2(160) NOT NULL,
    CREATED_DATE DATE NOT NULL,
    CREATED_BY VARCHAR2(16) NOT NULL,
    UPDATED_DATE DATE,
    UPDATED_BY VARCHAR2(16),
    ACTIVE VARCHAR2(1),
    ROOM_DESC VARCHAR2(2000)
    CREATE TABLE LOCATION
    ID NUMBER NOT NULL,
    NAME VARCHAR2(240) NOT NULL,
    ADDRESS VARCHAR2(240),
    PCODE VARCHAR2(8),
    CREATED_DATE DATE NOT NULL,
    CREATED_BY VARCHAR2(16) NOT NULL,
    UPDATED_DATE DATE,
    UPDATED_BY VARCHAR2(16),
    CONF_RDF VARCHAR2(10),
    CLOSING VARCHAR2(5),
    EVENING_START VARCHAR2(5)
    CREATE TABLE ROOM_PRICES
    ROOM NUMBER NOT NULL,
    FROM_DATE DATE NOT NULL,
    HOURLY NUMBER(6,2),
    HALF_DAY NUMBER(6,2),
    DAILY NUMBER(6,2),
    DISCOUNTABLE VARCHAR2(1),
    CREATED_DATE DATE NOT NULL,
    CREATED_BY VARCHAR2(16) NOT NULL,
    UPDATED_DATE DATE,
    UPDATED_BY VARCHAR2(16),
    SURCHARGE NUMBER(6,2)
    Insert into bookings
    (ID, ROOM, CUSTOMER, BOOK_FROM, BOOK_TO, CONFIG, CREATED_DATE, CREATED_BY, UPDATED_DATE, UPDATED_BY, DELEGATES, NARRATIVE, CONTACT_DETAILS, CONFIRMED, FLAT_RATE, PRE_STANDBY_TIME, PRE_STANDBY)
    Values
    (9272, 7466, 4946, TO_DATE('10/25/2005 10:00:00', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('10/25/2005 13:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'Default', TO_DATE('10/27/2005 15:35:02', 'MM/DD/YYYY HH24:MI:SS'), 'HSIS0201', TO_DATE('10/27/2005 15:36:26', 'MM/DD/YYYY HH24:MI:SS'), 'HSIS0201', 1, 'another meeting', 'Hazel', 'Y', 40, TO_DATE('10/25/2005 09:30:00', 'MM/DD/YYYY HH24:MI:SS'), 1800);
    Insert into customer
    (ID, CUSTOMER, CONTACT_ADDRESS, CONTACT_TELEPHONE, CREATED_DATE, CREATED_BY, CUST_TYPE, BC_CONTACT)
    Values
    (4946, 'Association of Teachers', 'Address', '0191 8887777', TO_DATE('09/22/2003 08:05:47', 'MM/DD/YYYY HH24:MI:SS'), 'Dataload', 'B', 'Miss Jones');
    Insert into rooms
    (ID, LOC, NAME, CREATED_DATE, CREATED_BY, UPDATED_DATE, UPDATED_BY, ACTIVE)
    Values
    (7466, 308, ' Counselling Room 1', TO_DATE('04/11/2005 10:55:33', 'MM/DD/YYYY HH24:MI:SS'), 'BJAC1906', TO_DATE('06/22/2005 14:43:50', 'MM/DD/YYYY HH24:MI:SS'), 'HSIS0201', 'Y');
    Insert into location
    (ID, NAME, ADDRESS, PCODE, CREATED_DATE, CREATED_BY, UPDATED_DATE, UPDATED_BY, CONF_RDF, CLOSING, EVENING_START)
    Values
    (308, 'Business Centre', 'Address', 'NE30 1NT', TO_DATE('03/19/2003 13:07:35', 'MM/DD/YYYY HH24:MI:SS'), 'BJAC1906', TO_DATE('06/09/2005 11:17:09', 'MM/DD/YYYY HH24:MI:SS'), 'BJAC1906', 'BKCF_2', '22:30', '18:00');
    Thanks,
    Hazel

Maybe you are looking for

  • Need help using Apple Remote Desktop for remote family members

    I am new to ARD and need help. I know there are solutions to do what I am trying to do through LogMeIn and Teamviewer - but I have LogMein right now and the free edtition is going away and I think Teamviewer will do the same sooner or later. I have r

  • Work center decision

    Dear all, Ex- Reactor is main work center main  , under this we r having different type of reactors like R1,R2, R3 my client want to maintain main rector(work center) in master recipt, and they  will take a perticular work center decision at time of

  • How do you configure AMS to stream flash files from my dedicated virtual server?

    I would like to stream files from my dedicated virtual server instead of my computer. Is it possible to configure AMS so that I can do this? Any help would be appreciated. Thanks!

  • AHHHH! How do I turn off the "auto indent" in Word?

    Auto indent probably isn't the correct term, but I don't know what else to call it. I'm trying to write a paper, and for my works cited I need to indent certain lines. Well, it indents the whole paragraph and not just one line. So how do I turn this

  • Indesign CS4 and Indesign CS5 on new imac TOGETHER!

    Hi, I am purchasing a brand new imac (27in., quad core i5) which comes with the Apple Snow Leopard OS. I am also purchasing the CS5 master collection. A company that I freelance for is still using CS4 and wants me to create print layouts for them wit