Help with sql - Left Join

Hi,
Below are the details of what I am attempting to do.
DB version: 10.2.0.4.0
Sample Table Definition
create table t_cnf
conf_id number,
conf_value number,
conf_cat_id number,
actv_flg    char(1)
create table t_int_act
int_acc_id   number,
frst_mrch_id number,
create_date  date
create table t_int_act_cast
int_acc_id   number,
cast_id      number
create t_cast_alt_nmnt
cas_alt_nmt_id number,
cas_alt_id     number,
cast_id        number,
enrl_flg       char(1),
src_id         number
);Sample Data
insert into t_cnf values (1, 78965098, 12, 'Y');
insert into t_cnf values (1, 78965098, 13, 'Y');
insert into t_int_act values (234,78965098, trunc(sysdate) - 1);
insert into t_int_act_cast values (234, 560432);
insert into t_cas_alt_nmnt values (1, 2, 560432, 'Y', 2); Need to fetch all cast_ids that are not in t_cast_alt_nmnt or cast_ids that are present in t_cast_alt_nmnt but have t_cast_alt_nmnt.enrl_flg = 'N' and t_cast_alt_nmnt.cast_alt_id in (2,3) and t_cast_alt_nmnt.src_id <> 2
for t_int_act.frst_mrch_ids matching t_cnf.conf_vale
Records fetch will insert a record into t_cast_alt_nmnt with css_alt_id 2 or 3 (determined by pe_or_pd).
I attempted to write below sql. This works fine when cast_id does not exists in t_cast_alt_nmnt but will not return correct results when there is a record in t_cast_alt_nmnt matching above criteria.
select
    iac.cast_id                            cast_id,
    sysdate                                upd_date,               
    case
        when c.conf_cat_id = 12 then 2
        when c.conf_cat_id = 13 then 3
    end
        pe_or_pd           
from
    t_cnf                  c
join    
    t_int_act          ia
on
    ia.frst_mrch_id = c.conf_value
join              
    t_int_act_cast iac
on
    ia.int_acc_id = iac.int_acc_id
left join       
    t_cast_alt_nmnt     can
on
    can.cast_id = iac.cast_id     and
    can.enrl_flg = 'N'            and
    can.cas_alt_id in (2,3)       and
    can.src_id <> 2      
where                 
    c.conf_cat_id              in (12,13)                           and
    c.actv_flg                 = 'Y'                                and
    -- Fetch all new customer created day before.   
    ia.create_date             >= trunc(sysdate) - 1                   
    Expected results
With no cast_id record in t_cast_alt_nmnt
cast_id upd_date pe_or_pd
560432 4/19/2012 2
560432 4/19/2012 3
With cast_id record in t_css_alt_nmt (insert provided)
cast_id upd_date pe_or_pd
560432 4/19/2012 3
Appreciate your help
Edited by: user572194 on Apr 19, 2012 1:04 PM

Thanks Frank for taking time to look into this and providing sql. I will test is against use cases (mentioned below).
And I apologize for the typos. I had to change table and column names as it is policy of our company not to post data model details in public forums.
Requirement:
1. New cast ids will be added daily and these will get inserted into t_int_act and t_int_act_cas
2. t_cnf has 2 conf_cat_id configured 12 and 13 and each conf_cat_id will have same conf_values (same as t_int_act.frst_mrch_id) but actv_flg might be different (set to N for 12 and Y for 13). Need to fetch only active ones
3. t_cas_alt_nmnt will have cast_ids that are enrolled to receive certain mails if enrl_flg is Y for these. Not all cast_ids will have record in this table.
When a cast_id is enrolled by customer service, a record will get inserted with src_id = 2.
4. Requirement is to enroll new cast_ids created with frst_mrch_id matching t_cnf.conf_value where conf_cat_id in (12,13)
Match criteira:
If t_int_act_cas.cast_id exists in t_cas_alt_nmnt and have enrl_flg = 'Y' for cas_alt_id = 2 then
insert record with same cast_id, enrl_flg = 'Y' and css_alt_id = 3
If t_int_act_cas.cast_id exists in t_cas_alt_nmnt and have enrl_flg = 'Y' for cas_alt_id = 3 then
insert record with same cast_id, enrl_flg = 'Y' and css_alt_id = 2
If t_int_act_cas.cast_id exists in t_cas_alt_nmnt and have enrl_flg = 'N' for cas_alt_id in (2,3) and src_id = 2 then
Ignore this record.
if t_int_act_cas.cast_id not exists in t_cas_alt_nmnt then
insert 1 record each with cast_id, enrl_flg = 'Y' for css_alt_id 2 and 3
Hope above explanation makes sense.
By the way I tried below sql. Yet to test it for all use cases but it worked for the last two.
Note on PE_OR_PD column. I am just using this column to write separate inserts for css_alt_id 2 and 3.
select
     cast_id,
     upd_date,
     pe_or_pd
from    
     (select
                iac.cast_id                        cast_id,
                sysdate                            upd_date,
                case
                    when c.conf_cat_id = 12 and can.cas_alt_id in (2,3) and enrl_flg = 'Y' then null
                    when c.conf_cat_id = 13 and can.cas_alt_id in (2,3) and enrl_flg = 'Y' then null
                    when c.conf_cat_id = 12 and nvl(can.cas_alt_id,2) = 2 and nvl(can.enrl_flg,'Y') = 'N' and can.src_id <> 2 then 'PE'
                    when c.conf_cat_id = 13 and nvl(can.cas_alt_id,3) = 3 and nvl(can.enrl_flg,'Y') = 'N' and can.src_id <> 2 then 'PD'       
                    when c.conf_cat_id = 12 and nvl(can.cas_alt_id,2) = 2 and nvl(can.enrl_flg,'Y') = 'Y' then 'PE'                                                                     
                    when c.conf_cat_id = 13 and nvl(can.cas_alt_id,3) = 3 and nvl(can.enrl_flg,'Y') = 'Y' then 'PD'                                                          
                end
                    pe_or_pd              
            from
                t_cnf              c,   
                t_int_act          ia,      
                t_intl_act_cus     iac,
                t_cas_alt_nmnt     can              
            where
                c.conf_value               = ia.frst_mrch_id               and
                ia.internal_account_id     = iac.int_act_id                and 
                can.cast_id(+)             = iac.cast_id                   and                               
                c.conf_cat_id              in (12,13)                      and
                c.actv_flg                 = 'Y'                           and
                -- Fetch all new customer created after last run.   
                ia.create_date             >= trunc(sysdate) - 1                                                                     
     ) enrl_cust
where
    pe_or_pd is not null               
                ;

Similar Messages

  • Need help with SQL Query with Inline View + Group by

    Hello Gurus,
    I would really appreciate your time and effort regarding this query. I have the following data set.
    Reference_No---Check_Number---Check_Date--------Description-------------------------------Invoice_Number----------Invoice_Type---Paid_Amount-----Vendor_Number
    1234567----------11223-------------- 7/5/2008----------paid for cleaning----------------------44345563------------------I-----------------*20.00*-------------19
    1234567----------11223--------------7/5/2008-----------Adjustment for bad quality---------44345563------------------A-----------------10.00------------19
    7654321----------11223--------------7/5/2008-----------Adjustment from last billing cycle-----23543556-------------------A--------------------50.00--------------19
    4653456----------11223--------------7/5/2008-----------paid for cleaning------------------------35654765--------------------I---------------------30.00-------------19
    Please Ignore '----', added it for clarity
    I am trying to write a query to aggregate paid_amount based on Reference_No, Check_Number, Payment_Date, Invoice_Number, Invoice_Type, Vendor_Number and display description with Invoice_type 'I' when there are multiple records with the same Reference_No, Check_Number, Payment_Date, Invoice_Number, Invoice_Type, Vendor_Number. When there are no multiple records I want to display the respective Description.
    The query should return the following data set
    Reference_No---Check_Number---Check_Date--------Description-------------------------------Invoice_Number----------Invoice_Type---Paid_Amount-----Vendor_Number
    1234567----------11223-------------- 7/5/2008----------paid for cleaning----------------------44345563------------------I-----------------*10.00*------------19
    7654321----------11223--------------7/5/2008-----------Adjustment from last billing cycle-----23543556-------------------A--------------------50.00--------------19
    4653456----------11223--------------7/5/2008-----------paid for cleaning------------------------35654765-------------------I---------------------30.00--------------19
    The following is my query. I am kind of lost.
    select B.Description, A.sequence_id,A.check_date, A.check_number, A.invoice_number, A.amount, A.vendor_number
    from (
    select sequence_id,check_date, check_number, invoice_number, sum(paid_amount) amount, vendor_number
    from INVOICE
    group by sequence_id,check_date, check_number, invoice_number, vendor_number
    ) A, INVOICE B
    where A.sequence_id = B.sequence_id
    Thanks,
    Nick

    It looks like it is a duplicate thread - correct me if i'm wrong in this case ->
    Need help with SQL Query with Inline View + Group by
    Regards.
    Satyaki De.

  • Need help with an Outer Join

    I have the following query which has an outer join and it works perfectly and shows publication paragraph which don't have any maintenance records with a value of 0.
    However when I add to the where clause conditions such as lpm.fac_ident and lpm.start_date, the null values no longer show up in the query(see second SQL statement).
    I am new at SQL and am just trying to make this outer join work. Any help would be appreciated.
    -- THIS WORKS
    SELECT m.publication_paragraph, pm.description, pm.frequency, count(l.publication_paragraph) ACTIVITIES_PERFORMED
    FROM lpm_paragraph_mapping_table m, lpm l, pm_requirements_table pm
    WHERE m.paragraph_alias_mapping = l.publication_paragraph (+)
    GROUP BY m.publication_paragraph, pm.description, pm.frequency
    order by count(l.publication_paragraph);
    -- THIS DOES NOT WORK
    SELECT m.publication_paragraph, pm.description, pm.frequency, count(l.publication_paragraph) ACTIVITIES_PERFORMED
    FROM lpm_paragraph_mapping_table m, lpm l, pm_requirements_table pm
    WHERE m.paragraph_alias_mapping = l.publication_paragraph (+)
    AND l.fac_ident = 'EWR' AND TO_CHAR(l.start_date, 'YYYY') = '2010'
    GROUP BY m.publication_paragraph, pm.description, pm.frequency
    order by count(l.publication_paragraph);
    Edited by: George Heller on Jun 30, 2011 9:47 AM

    fabio_silva wrote:
    Hi,
    I just didn't get. The table (pm_requirements_table pm) haven't any join ???
    Regards,Forgive the ASCII art, but your query looks like:
    ----------  JOIN ----------
    | Alias M | ====> | Alias L |
    | Alias PM |
    ----------- The table pm_requirements_table is not joined at all. Unless it has only a single row, then your resultset will have 1 row for each row in lpm_paragraph_mapping_table (because of the outer join) times the number of rows in pm_requirements_table. Consider this simplified example.
    SQL> select * from t;
            ID DESCR
             1 T 1
             2 T 2
    SQL> select * from t1;
            ID DESCR
             1 T1 1
             2 T1 2
             3 T1 3
             4 T1 4
    SQL> select 1.id, t.descr, t1.descr
      2  from t, t1;
            ID DESCR      DESCR
             1 T 1        T1 1
             1 T 1        T1 2
             1 T 1        T1 3
             1 T 1        T1 4
             1 T 2        T1 1
             1 T 2        T1 2
             1 T 2        T1 3
             1 T 2        T1 4Here, my table t is the result from your join between lpm_paragraph_mapping_table and lpm. My table t1 is your pm_requirements_table. You need something more like:
    SQL> select 1.id, t.descr, t1.descr
      2  from t, t1
      3  where t.id = t1.id;
            ID DESCR      DESCR
             1 T 1        T1 1
             1 T 2        T1 2Assuming you fix that join, you can use a sub-query to apply the predicates to the lpm as Centinul showed, or, if you are on a current version of Oracle, use ANSI join syntax wich would look something like:
    SELECT m.publication_paragraph, pm.description, pm.frequency,
            count(l.publication_paragraph) ACTIVITIES_PERFORMED
    FROM lpm_paragraph_mapping_table m,
       LEFT JOIN lpm l,
          ON m.paragraph_alias_mapping = l.publication_paragraph and
             l.fac_ident = 'EWR' AND
             TO_CHAR(l.start_date, 'YYYY') = '2010'
       JOIN pm_requirements_table pm
          on something
    GROUP BY m.publication_paragraph, pm.description, pm.frequency
    ORDER BY count(l.publication_paragraph);Leaving aside the missing join, the reason why your query as posted does not work is that when there is not a match on m.paragraph_alias_mapping = l.publication_paragraph Oracle will "make up" rows form lpm with all null columns for each row in lpm_paragraph_mapping_table where there is no match. So, when you compare those made up rows from lpm, you are effectively saying where NULL = 'EWR' and TO_CHAR(NULL, 'yyyy') = '2010'. Null is never equal to anything. Any comparision against null is unknown, so the made up rows get filtered out by your predicate.
    John

  • Help with SQL Query - MIN MAX - CTE?

    First and foremost, the SQL is handled dynamically - please ignore some of the crazy coding you see in the WHERE clauses ... its not an issue with the report, trust me.
    What my client needs is a summary by Facility, by Resource for each specific day - broken out in 3 distinct time blocks for that specific Resource at each distinct facility. For each Resource by Facility I need 3 rows - a row for their earliest AM appointment
    to their latest AM appointment (AMStart and AMStop below) - a row for their earliest PM appointment to their latest PM appointment (PMStart and PMStop below) and finally a row for their EVE appointments (EVEStart and EVEStop below).
    I thought doing a MIN and MAX on them would fix this and grouping it but I am missing something because my times for my AM are way off. For my test provider, I have set up a schedule that starts at 7:15 AM and spans to 11:45 AM. I created a break and had
    him re-start at 1:00 PM and go to 2:45 PM. No Evening clinic was made on this example.
    What I would hope to get back is 3 rows - an AM row with the earliest AMStart and latest AMStop time (with the PM and EVE pull NULL), a PM row(earliest and latest) (with the AM and EVE pull NULL) and finally my EVE with same concept.
    My current data set (1 row) - should have as 3 rows and my AM Start and Stop are wrong.
    Scheduledate = 01/21/2014      
    AMStart  = 10:00AM
    AMStop =  9:45AM      
    PMStart =       1:00PM
    PMStop =       2:45PM
    EveStart =       NULL
    EveStop =       NULL
    TotalTime = 375      
    Resource = Bailey MD, William R
    Facility = River Oaks
    /*Appointment Times report*/
    SET NOCOUNT ON
    DECLARE @Today DATETIME
    DECLARE @Tomorrow DATETIME
    SET @Today = '01/21/2014'
    SET @Tomorrow = DATEADD(d , 1 , '01/21/2014')
    DECLARE @tblTemp TABLE
    ApptSlotId INT ,
    Resource VARCHAR(60) ,
    ResourceId INT ,
    Start DATETIME ,
    Stop DATETIME ,
    AMStart DATETIME ,
    AMStop DATETIME ,
    PMStart DATETIME ,
    PMStop DATETIME ,
    EveStart DATETIME ,
    EveStop DATETIME ,
    Patient VARCHAR(256) ,
    [Column] VARCHAR(64) ,
    Facility VARCHAR(60) ,
    FacilityId INT ,
    Allocations VARCHAR(4096) ,
    Scheduledate VARCHAR(15)
    INSERT INTO @tblTemp
    SELECT
    ApptSlotid ,
    d.Listname ,
    d.DoctorFacilityId ,
    Start ,
    Stop ,
    NULL ,
    NULL ,
    NULL ,
    NULL ,
    NULL ,
    NULL ,
    ' ' AS Patient ,
    CAST(aps.ListOrder AS VARCHAR(10)) AS [Column] ,
    f.ListName AS Facility ,
    aps.FacilityId ,
    dbo.sfnGetAllocsForSlot(aps.ApptSlotId) AS Allocations ,
    CONVERT(VARCHAR(15) , Start , 101)
    FROM
    ApptSlot aps
    JOIN Schedule s ON aps.ScheduleId = s.ScheduleId
    JOIN DoctorFacility df ON s.DoctorResourceId = df.DoctorFacilityId
    JOIN DoctorFacility f ON aps.FacilityId = f.DoctorFacilityId
    JOIN DoctorFacility d ON s.DoctorResourceId = d.DoctorFacilityId
    WHERE
    --Filter on resource
    NULL IS NOT NULL
    AND s.Doctorresourceid IN ( NULL )
    OR ( NULL IS NULL )
    AND (
    NULL IS NOT NULL
    AND aps.FacilityId IN ( NULL )
    OR ( NULL IS NULL )
    AND (
    Start >= @Today
    OR @Today IS NULL
    AND (
    Start < @Tomorrow
    OR @Tomorrow IS NULL
    AND ApptId IS NULL
    AND APS.ListOrder <> -1
    INSERT INTO @tblTemp
    SELECT DISTINCT
    ApptSlotid ,
    d.ListName ,
    d.DoctorFacilityId ,
    ApptStart ,
    ApptStop , -- need distinct because =ApptSlot can have more than row per appt
    NULL ,
    NULL ,
    NULL ,
    NULL ,
    NULL ,
    NULL ,
    CASE WHEN a.ApptKind = 1 THEN pp.Last + ', ' + pp.First
    WHEN a.ApptKind = 2 THEN 'Doctor Appt'
    WHEN a.ApptKind = 3 THEN 'Resource Appt'
    WHEN a.ApptKind = 5 THEN 'Block Out Appt'
    ELSE ''
    END AS Patient ,
    CASE WHEN aps.ListOrder IS NULL THEN 'Overbooked'
    ELSE CAST(aps.ListOrder AS VARCHAR(10))
    END AS [Column] ,
    f.ListName AS Facility ,
    a.FacilityId ,
    ISNULL(apt.Name , '<No Appointment Type>') AS Allocations ,
    CONVERT(VARCHAR(15) , ApptStart , 101) AS Scheduledate
    FROM
    Appointments a
    JOIN DoctorFacility f ON a.FacilityId = f.DoctorFacilityId
    LEFT JOIN PatientProfile pp ON a.OwnerId = pp.PatientProfileId
    LEFT JOIN ApptSlot aps ON a.AppointmentsId = aps.ApptId
    JOIN DoctorFacility d ON a.ResourceId = d.DoctorFacilityId
    LEFT JOIN ApptType apt ON a.ApptTypeId = apt.ApptTypeId
    WHERE
    NULL IS NOT NULL
    AND a.ResourceId IN ( NULL )
    OR ( NULL IS NULL )
    AND (
    NULL IS NOT NULL
    AND a.FacilityId IN ( NULL )
    OR ( NULL IS NULL )
    AND (
    ApptStart >= @Today
    OR @Today IS NULL
    AND (
    ApptStop < @Tomorrow
    OR @Tomorrow IS NULL
    AND (
    (ApptKind = 1
    AND ISNULL(Canceled , 0) = 0)
    UPDATE
    @tblTemp
    SET
    AMStart = Start ,
    AMStop = Stop
    FROM
    @tblTemp base
    WHERE
    CONVERT(TIME , start) < CONVERT(TIME , '12:00')
    UPDATE
    @tblTemp
    SET
    PMStart = Start ,
    PMStop = Stop
    FROM
    @tblTemp base
    WHERE
    CONVERT(TIME , start) > CONVERT(TIME , '12:00')
    AND CONVERT(TIME , start) < CONVERT(TIME , '17:00')
    UPDATE
    @tblTemp
    SET
    EveStart = Start ,
    EveStop = Stop
    FROM
    @tblTemp base
    WHERE
    CONVERT(TIME , start) > CONVERT(TIME , '17:00')
    --SELECT * FROM @tblTemp ORDER BY Start
    SELECT
    Scheduledate ,
    Start ,
    Stop ,
    [Column] ,
    Resource ,
    Facility ,
    CONVERT(VARCHAR(60) , CAST(CONVERT(VARCHAR(60) , h.AMStart , 108) AS TIME) , 100) AS AMStart ,
    CONVERT(VARCHAR(60) , CAST(CONVERT(VARCHAR(60) , h.AMStop , 108) AS TIME) , 100) AS AMStop ,
    CONVERT(VARCHAR(60) , CAST(CONVERT(VARCHAR(60) , h.PMStart , 108) AS TIME) , 100) AS PMStart ,
    CONVERT(VARCHAR(60) , CAST(CONVERT(VARCHAR(60) , h.PMStop , 108) AS TIME) , 100) AS PMStop ,
    CONVERT(VARCHAR(60) , CAST(CONVERT(VARCHAR(60) , h.EveStart , 108) AS TIME) , 100) AS EveStart ,
    CONVERT(VARCHAR(60) , CAST(CONVERT(VARCHAR(60) , h.EveStop , 108) AS TIME) , 100) AS EveStop ,
    ISNULL(DATEDIFF(MI , h.AMStart , h.AMStop) , 0) + ISNULL(DATEDIFF(MI , h.PMStart , h.PMStop) , 0) + ISNULL(DATEDIFF(MI , h.EveStart , h.EveStop) , 0) AS TotTime
    INTO
    #tmp
    FROM
    @TblTemp h
    WHERE
    [Column] = 1
    ORDER BY
    START
    --SELECT * FROM #tmp
    SELECT
    Scheduledate ,
    MIN(AMStart) AS AMStart ,
    MAX(AMStop) AS AMStop ,
    MIN(PMStart) AS PMStart ,
    MAX(PMStop) AS PMStop ,
    MIN(EveStart) AS EveStart ,
    MAX(EveStop) AS EveStop ,
    SUM(TotTime) AS TotalTime ,
    Resource ,
    Facility
    FROM
    #tmp
    GROUP BY
    Resource ,
    Facility ,
    Scheduledate
    DROP TABLE #tmp
    SET NOCOUNT OFF

    Since there is some context missing, I don't get everything, but from your narrative, it seems likely you need something like:
    WITH CTE AS (
       SELECT keycol,
              period = CASE WHEN Start < '12:00' THEN 'AM'
                            WHEN Start < '17:00' THEN 'PM'
                            ELSE 'EVE'
                       END,
              start, stop
       FROM   tbl
    SELECT keycol, period, MIN(start), MAX(stop)
    FROM   CTE
    GROUP  BY keycol, period
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Inconsistent results with ANSI LEFT JOIN on 9iR2

    Is this a known issue? Is it solved in 10g?
    With the following data setup, I get inconsistent results. It seems to be linked to the combination of using LEFT JOIN with the NULL comparison within the JOIN.
    create table titles (title_id int, title varchar(50));
    insert into titles values (1, 'Red Book');
    insert into titles values (2, 'Yellow Book');
    insert into titles values (3, 'Blue Book');
    insert into titles values (4, 'Orange Book');
    create table sales (stor_id int, title_id int, qty int, email varchar(60));
    insert into sales values (1, 1, 1, '[email protected]'));
    insert into sales values (1, 2, 1, '[email protected]');
    insert into sales values (3, 3, 4, null);
    insert into sales values (3, 4, 5, '[email protected]');
    SQL&gt; SELECT titles.title_id, title, qty
    2 FROM titles LEFT OUTER JOIN sales
    3 ON titles.title_id = sales.title_id
    4 AND stor_id = 3
    5 AND sales.email is not null
    6 ;
    TITLE_ID TITLE QTY
    4 Orange Book 5
    3 Blue Book
    1 Red Book
    2 Yellow Book
    SQL&gt;
    SQL&gt; SELECT titles.title_id, title, qty
    2 FROM titles LEFT OUTER JOIN sales
    3 ON titles.title_id = sales.title_id
    4 AND 3 = stor_id
    5 AND sales.email is not null;
    TITLE_ID TITLE QTY
    2 Yellow Book 1
    4 Orange Book 5
    3 Blue Book
    1 Red Book
    It seems to matter what order I specify the operands stor_id = 3, or 3 = stor_id.
    In the older (+) environment, I would understand this, but here? I'm pretty sure most other databases don't care about the order.
    thanks for your insight
    Kevin

    Don't have a 9i around right now to test ... but in 10 ...
    SQL> create table titles (title_id int, title varchar(50));
     
    Table created.
     
    SQL> insert into titles values (1, 'Red Book');
     
    1 row created.
     
    SQL> insert into titles values (2, 'Yellow Book');
     
    1 row created.
     
    SQL> insert into titles values (3, 'Blue Book');
     
    1 row created.
     
    SQL> insert into titles values (4, 'Orange Book');
     
    1 row created.
     
    SQL> create table sales (stor_id int, title_id int, qty int, email varchar(60));
     
    Table created.
     
    SQL> insert into sales values (1, 1, 1, '[email protected]');
     
    1 row created.
     
    SQL> insert into sales values (1, 2, 1, '[email protected]');
     
    1 row created.
     
    SQL> insert into sales values (3, 3, 4, null);
     
    1 row created.
     
    SQL> insert into sales values (3, 4, 5, '[email protected]');
     
    1 row created.
     
    SQL> SELECT titles.title_id, title, qty
      2   FROM titles LEFT OUTER JOIN sales
      3   ON titles.title_id = sales.title_id
      4   AND stor_id = 3
      5   AND sales.email is not null
      6   ;
     
      TITLE_ID TITLE                                                     QTY
             4 Orange Book                                                 5
             3 Blue Book
             1 Red Book
             2 Yellow Book
     
    SQL>
    SQL> SELECT titles.title_id, title, qty
      2   FROM titles LEFT OUTER JOIN sales
      3   ON titles.title_id = sales.title_id
      4   AND 3 = stor_id
      5   AND sales.email is not null;
     
      TITLE_ID TITLE                                                     QTY
             4 Orange Book                                                 5
             3 Blue Book
             1 Red Book
             2 Yellow Book
    SQL> exit
    Disconnected from Oracle Database 10g Enterprise Edition Release 10.1.0.2.0 - Production
    With the Partitioning, OLAP and Data Mining options

  • Help with multiple table joins

    I'm trying to limit the results of a query joining multiple tables. I have a main table, tbl_webrequests, and multiple tables with supporting information. The unique column for tbl_webrequests is reqID. There is another table, tbl_instructions, that holds all the instructions tied to each request. I join the tables using reqID.
    I'm trying to construct a page that has all of the records in tbl_webrequests. The problem I'm having is that with each request that has multiple instructions, I have multiple results because of the multiple instructions for one reqID. For now, all I want is the original instruction to display. Below is the original query, and below that is what I'm trying to get the query to do for each record in tbl_webrequest. Note that 319 is a random uniqueID in tbl_webrequests.
    SELECT
    DISTINCT W.reqID, W.dt_close, W.dt_due, W.subject, W.statusid, W.empID, W.priorityid, W.assigneeid, W.categoryid, W.url, W.hrs,
    W.closingNotes, W.mins, W.requestTypeID, I.instructions, I.instID
    from tbl_webrequests W left join
    (select reqID, instID, instructions from tbl_instructions) I on W.reqID = I.reqID
    ORDER BY I.instID asc;
    SELECT
    distinct I.instructions, I.instID, W.reqID, W.dt_close, W.dt_due, W.subject, W.statusid, W.empID, W.priorityid, W.assigneeid, W.categoryid, W.url, W.hrs,
    W.closingNotes, W.mins, W.requestTypeID
    from tbl_webrequests W left join
    (select reqID, instID, instructions from tbl_instructions where rowNum = 1 and reqid = 319 order by instID asc) I on W.reqID = I.reqID
    where W.reqID = 319
    ORDER BY I.instID asc;
    My question is, how do I pass the reqID as a variable into the join subquery so that the query returns only returns the first joined item in tbl_instructions for each record in tbl_webrequests?
    Any help is appreciated
    Thanks!

    Scrap the "DISTINCT" and try something like this:
    Select
           I.Instructions, I.Instid
         , W.Reqid, W.Dt_Close, W.Dt_Due, W.Subject, W.Statusid, W.Empid, W.Priorityid
         , W.Assigneeid, W.Categoryid, W.Url, W.Hrs, W.Closingnotes, W.Mins, W.Requesttypeid
      From Tbl_Webrequests W Left Join
         ( Select Reqid, Instid, Instructions
             From Tbl_Instructions I0
            Where Instid = (Select Min(Instid) From Tbl_Instructions I1
                             Where I1.Reqid = I0.Reqid)
         ) I On W.Reqid = I.Reqid
    Where W.Reqid = 319
    Order By I.Instid Asc;;)

  • Where clause "where 1=1" help with SQL tuning

    Hello Tuning experts,
    Is it helpful to use "where 1=1" and then put all the joins and conditions in the "AND" statements of the SQL when writing SQL queries. I would like to know if it helps with query performance to write SQL queirs that way.
    Thanks in advance.
    Edited by: oracle_developer on Oct 8, 2012 10:41 AM

    You can see here that "where 1 = 1" is gone from the predicate info in the explain plan.
    The optimizer simply discarded it.
    SQL> explain plan for
      2  select *
      3  from emp
      4  where 1 = 1
      5  and job = 'SALESMAN';
    Explained.
    PLAN_TABLE_OUTPUT
    Plan hash value: 3956160932
    | Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT  |      |     3 |   114 |     3   (0)| 00:00:01 |
    |*  1 |  TABLE ACCESS FULL| EMP  |     3 |   114 |     3   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       1 - filter("JOB"='SALESMAN')
    13 rows selected.

  • Having issues with a left join, getting ORA-00904 error

    Ok this is something very similar to what I am facing, but dumbed down. None of these columns or tables names exist in real life (Very paranoid company I work for, understandable though) but the fundamental problem I am having is like below.
    Basically I know I could have done something similar to this is MS SQL (Or am I dreaming?). If I am right or wrong I need to know a way around this.
    Obviously if you comment out the "CAL.WEEK_SINCE_2005" and "AND CUST.week_since_2005 = CAL.WEEK_SINCE_2005" it would work. But I really need it to display the date as well. So it can be group'ed by week since 2005.
    I will be joining other statements to this. I am hoping on doing this in one select statement instead of creating multiple tables as I am now. All the other joined tables will follow a VERY similar layout to this. So something like this is need to obtain the look.
    When ran I get the following error.
    I look forward to learning what I did wrong and how I can fix it. :)
    select ORG.ORGANIZATION_NAME,
    CUST.CUST_COUNT,
    CAL.WEEK_SINCE_2005
    FROM organization ORG,
    calendar CAL
    LEFT JOIN (
    SELECT CAP.CURRENT_STORE,
    CALEN.week_since_2005,
    count(CAP.inactive_date) CUST_COUNT
    FROM CUST_AGREE_PAST CAP,
    calendar CALEN
    WHERE CAP.active_date is not null
    and CAP.inactive_code in ('T')
    and CAP.inactive_date between '01-sep-07' and sysdate
    and CAP.INACTIVE_DATE = CALEN.CALENDAR_DATE
    and CAP.RSN_CODE_ID in (select rsn_code_id from reasons where title in ('FAIL', 'NO CALL'))
    GROUP BY CAP.CURRENT_STORE,
    CALEN.week_since_2005) CUST
    ON PO.CURRENT_STORE = ORG.ORGANIZATION_NAME
    AND CUST.week_since_2005 = CAL.WEEK_SINCE_2005

    Just noticed a problem (there might be others):
    FROM organization ORG,
    calendar CAL
    LEFT JOIN (You cannot do that - you are mixing Oracle and ANSI join syntax. You have to do one or the other:
    FROM organization ORG
    JOIN calendar CAL on (ORG.col = CAL.col)
    LEFT JOIN (....)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Where to find help with SQL Developer installation?

    Hi,
    I just want to try out SQL Developer and compare its capabilities to TOAD's. Unfortunately, I am not PC software savvy and now am stuck with a SQL Developer (sqldeveloper-1.2.2998) installation problem. When I clicked on the .exe file, I got a blank SQL Developer screen - there is nothing in the screen except a heading that reads 'Oracle SQL Developer'...
    Does anyone know of a blog or a site that I can get some help with problems like mine?
    Any help is much appreciated!

    Hi,
    SQL Developer forum link:
    "http://forums.oracle.com/forums/forum.jspa?forumID=260"
    There are 2 versions of SQL Developer, with/without JRE.
    Try out the full install version with JRE.
    HTH
    Zack

  • Need help with SQL*Loader not working

    Hi all,
    I am trying to run SQL*Loader on Oracle 10g UNIX platform (Red Hat Linux) with below command:
    sqlldr userid='ldm/password' control=issue.ctl bad=issue.bad discard=issue.txt direct=true log=issue.log
    And get below errors:
    SQL*Loader-128: unable to begin a session
    ORA-01034: ORACLE not available
    ORA-27101: shared memory realm does not exist
    Linux-x86_64 Error: 2: No such file or directory
    Can anyone help me out with this problem that I am having with SQL*Loader? Thanks!
    Ben Prusinski

    Hi Frank,
    More progress, I exported the ORACLE_SID and tried again but now have new errors! We are trying to load an Excel CSV file into a new table on our Oracle 10g database. I created the new table in Oracle and loaded with SQL*Loader with below problems.
    $ export ORACLE_SID=PROD
    $ sqlldr 'ldm/password@PROD' control=prod.ctl log=issue.log bad=bad.log discard=discard.log
    SQL*Loader: Release 10.2.0.1.0 - Production on Tue May 23 11:04:28 2006
    Copyright (c) 1982, 2005, Oracle. All rights reserved.
    SQL*Loader: Release 10.2.0.1.0 - Production on Tue May 23 11:04:28 2006
    Copyright (c) 1982, 2005, Oracle. All rights reserved.
    Control File: prod.ctl
    Data File: prod.csv
    Bad File: bad.log
    Discard File: discard.log
    (Allow all discards)
    Number to load: ALL
    Number to skip: 0
    Errors allowed: 50
    Bind array: 64 rows, maximum of 256000 bytes
    Continuation: none specified
    Path used: Conventional
    Table TESTLD, loaded from every logical record.
    Insert option in effect for this table: REPLACE
    Column Name Position Len Term Encl Datatype
    ISSUE_KEY FIRST * , CHARACTER
    TIME_DIM_KEY NEXT * , CHARACTER
    PRODUCT_CATEGORY_KEY NEXT * , CHARACTER
    PRODUCT_KEY NEXT * , CHARACTER
    SALES_CHANNEL_DIM_KEY NEXT * , CHARACTER
    TIME_OF_DAY_DIM_KEY NEXT * , CHARACTER
    ACCOUNT_DIM_KEY NEXT * , CHARACTER
    ESN_KEY NEXT * , CHARACTER
    DISCOUNT_DIM_KEY NEXT * , CHARACTER
    INVOICE_NUMBER NEXT * , CHARACTER
    ISSUE_QTY NEXT * , CHARACTER
    GROSS_PRICE NEXT * , CHARACTER
    DISCOUNT_AMT NEXT * , CHARACTER
    NET_PRICE NEXT * , CHARACTER
    COST NEXT * , CHARACTER
    SALES_GEOGRAPHY_DIM_KEY NEXT * , CHARACTER
    value used for ROWS parameter changed from 64 to 62
    Record 1: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 2: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 3: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 4: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 5: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 6: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 7: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 8: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 9: Rejected - Error on table ISSUE_FACT_TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 10: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 11: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 12: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 13: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 14: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 15: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 16: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 17: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 18: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 19: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 20: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 21: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 22: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 23: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 24: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 39: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    MAXIMUM ERROR COUNT EXCEEDED - Above statistics reflect partial run.
    Table TESTLD:
    0 Rows successfully loaded.
    51 Rows not loaded due to data errors.
    0 Rows not loaded because all WHEN clauses were failed.
    0 Rows not loaded because all fields were null.
    Space allocated for bind array: 255936 bytes(62 rows)
    Read buffer bytes: 1048576
    Total logical records skipped: 0
    Total logical records read: 51
    Total logical records rejected: 51
    Total logical records discarded: 0
    Run began on Tue May 23 11:04:28 2006
    Run ended on Tue May 23 11:04:28 2006
    Elapsed time was: 00:00:00.14
    CPU time was: 00:00:00.01
    [oracle@casanbdb11 sql_loader]$
    Here is the control file:
    LOAD DATA
    INFILE issue_fact.csv
    REPLACE
    INTO TABLE TESTLD
    FIELDS TERMINATED BY ','
    ISSUE_KEY,
    TIME_DIM_KEY,
    PRODUCT_CATEGORY_KEY,
    PRODUCT_KEY,
    SALES_CHANNEL_DIM_KEY,
    TIME_OF_DAY_DIM_KEY,
    ACCOUNT_DIM_KEY,
    ESN_KEY,
    DISCOUNT_DIM_KEY,
    INVOICE_NUMBER,
    ISSUE_QTY,
    GROSS_PRICE,
    DISCOUNT_AMT,
    NET_PRICE,
    COST,
    SALES_GEOGRAPHY_DIM_KEY
    )

  • Please help with SQL amount calulation

    -- Results
    with t as ( 
    select 'P11877' Mstr_Program,   1 Year_of_study, 'BUSI1490' program_module,  20 no_of_stud,    1 rank,   30 program_credits,  30 cumm_credits   from dual union all
    select 'P11877',                1,              'COMP1365',                 20,               2,        30,                  60               from dual union all
    select 'P11877',                1,              'BUSI1375',                 20,               3,        30,                  90               from dual union all
    select 'P11877',                1,              'COMP1363',                 20,               4,        30,                  120              from dual union all
    select 'P11877',                2,              'MARK1174',                 8,                1,        30,                  30               from dual union all
    select 'P11877',                2,              'FINA1068',                 8,                2,        15,                  45               from dual union all
    select 'P11877',                2,              'INDU1062',                 8,                3,        30,                  75               from dual union all
    select 'P11877',                2,              'BUSI1329',                 8,                4,        15,                  90               from dual union all
    select 'P11877',                2,              'MARK1138',                 8,                5,        30,                  120              from dual)
    select * from t;-- Each MSTR_PROGRAM can have 1 or many program_module
    -- MSTR_PROGRAM's can run for 1 or 2 years (case above is two years) so some modules run in year 1 and some in year 2
    -- NO_OF_STUD is the number of students on the module
    -- RANK basically ranks the modules by the number of students on them grouped by program and year
    -- e.g.row_number() OVER (PARTITION BY Mstr_Program, Year_of_study) ORDER BY COUNT(STUDENT_ID) DESC) rank
    -- PROGRAM_CREDITS: each module has a fixed number of credits
    -- CUMM_CREDITS: Increments the credit count of modules
    -- SUM(program_credits * 10) OVER (PARTITION BY Mstr_Program, Year_of_study
    -- ORDER BY count(STUDENT_ID) desc ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) cumm_credits
    -- I want to trim of any modules once the CUM_CREDITS hits 120. As seen above. I achieve this by wrapping the main query is another SELECT then LIMIT
    -- that WHERE cum_credit <=120.
    -- But what I need is:
    -- In some cases the the cumm_credit maybe on lets say 90credits then the next module is worth 40 credits. This next module will not show as it
    -- will be greater than 120 credits, so i need to pro-rata it:
    -- So if credit_count > 120, then the last module is counted pro-rata as follows: 1- ((credit count - 120) / credits from last module
    -- Can anyone help with how I can incorporate this into my current code: The SELECT portion of the Original SQL is below: I simplified column names
    -- e.t.c in the above so they wont be the same
    SELECT * FROM (
         SELECT
               ,SR_PROGRAM Mstr_Program
               ,DECODE (SORLCUR_YEAR, 1, 1,
                                      2, 2,
                                      3, 3,
                                      4, 3, SR_YEAR) year_of_study
               ,SCT_SUBJ_CODE||SCT_CRSE_NUMB program_module
               ,COUNT(student_ID)                    no_of_stud
               ,row_number() OVER (PARTITION BY sr_program,
                                            DECODE (sr_year, 1, 1,
                                                                  2, 2,
                                                                  3, 3,
                                                                  4, 3, SR_YEAR) ORDER BY COUNT(student_id) DESC, scbcrse_title asc) rank
               ,(SCT_CREDIT_HRS * 10) program_credits
               ,SUM(SCT_CREDIT_HRS * 10) OVER (PARTITION BY sr_program, DECODE (sorlcur_year, 1, 1,
                                                                                                       2, 2,
                                                                                                       3, 3,
                                                                                                       4, 3, SR_YEAR)
                                                    ORDER BY count(student_id) desc ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) cumm_credits
    WHERE cumm_credit <=120
    ORDER BY Mstr_Program, YEAR_OF_STUDY, RANK asc;

    Maybe
    SELECT Mstr_Program,year_of_study,program_module,no_of_stud,rank,program_credits old_program_credits,cumm_credits old_cumm_credits,
           case when cumm_credits > 120
                then program_credits - cumm_credits + 120
                else program_credits
           end new_program_credits,
           case when cumm_credits > 120
                then 120
                else cumm_credits
           end new_cumm_credits
      FROM (SELECT SR_PROGRAM Mstr_Program,
                   DECODE(SORLCUR_YEAR,1,1,2,2,3,3,4,3,SR_YEAR) year_of_study,
                   SCT_SUBJ_CODE||SCT_CRSE_NUMB program_module,
                   COUNT(student_ID) no_of_stud,
                   row_number() OVER (PARTITION BY sr_program,DECODE(sr_year,1,1,2,2,3,3,4,3,SR_YEAR)
                                          ORDER BY COUNT(student_id) DESC,scbcrse_title) rank,
                   10 * SCT_CREDIT_HRS program_credits,
                   10 * SUM(SCT_CREDIT_HRS) OVER (PARTITION BY sr_program,DECODE(sorlcur_year,1,1,2,2,3,3,4,3,SR_YEAR)
                                                      ORDER BY count(student_id) desc
                                                  ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) cumm_credits
    WHERE 0 <= case when cumm_credits > 120
                     then program_credits - cumm_credits + 120
                     else program_credits
                end
    ORDER BY Mstr_Program,YEAR_OF_STUDY,RANKRegards
    Etbin
    Edited by: Etbin on 16.12.2011 8:50
    with
    t as   /* simulating the result achieved */
    (select 'P11877' Mstr_Program,1 Year_of_study, 'BUSI1490' program_module,20 no_of_stud,1 rank,30 program_credits,30 cumm_credits from dual union all
    select 'P11877',             1,               'COMP1365',               20,           2,     40,                70              from dual union all
    select 'P11877',             1,               'BUSI1375',               20,           3,     30,                100             from dual union all
    select 'P11877',             1,               'COMP1363',               20,           4,     40,                140             from dual union all
    select 'P11877',             2,               'MARK1174',               8,            1,     30,                30              from dual union all
    select 'P11877',             2,               'FINA1068',               8,            2,     50,                80              from dual union all
    select 'P11877',             2,               'INDU1062',               8,            3,     30,                110             from dual union all
    select 'P11877',             2,               'BUSI1329',               8,            4,     50,                160             from dual union all
    select 'P11877',             2,               'MARK1138',               8,            5,     30,                190             from dual
    select Mstr_Program,Year_of_study,program_module,no_of_stud,rank,program_credits old_credits,cumm_credits old_cumm,
           case when cumm_credits > 120
                then program_credits - cumm_credits + 120
                else program_credits
           end new_program_credits,
           case when cumm_credits > 120
                then 120
                else cumm_credits
           end new_cumm_credits
      from t
    where 0 <= case when cumm_credits > 120
                     then program_credits - cumm_credits + 120
                     else program_credits
                end

  • Help with SQL Server 2005 http Endpoint

    I am trying to use mx:webservice to directly connect to a SQL
    Server 2005 HTTP Endpoint. Is this possible. Is there going to be a
    problem with crossdomain issues? If the Endpoint is actively
    listening on port 80 then IIS cannot. So I cannot place
    crossdomain.xml in webserver, how will I overcome this crossdomain
    problem? Am I making this more complicated than it is? If anyone
    has an example it would be appreciated. All I want is a flex2 app
    talking directly to sql server. Seems possible.

    Kent, I see that many others have reported that error (doing
    a google search), but I see no ready answers. I saw something that
    reminded me of a connection string value that I've seen answer some
    problems. May be worth a shot for you: try adding this string to
    the connection string (in "advanced options") for your datasource:
    AuthenticationMethod=Type2
    If it doesn't solve it, remove it. But keep it handy in case
    it ever may help with some other problem.
    Here's one other possible answer for you:
    http://www.webmasterkb.com/Uwe/Forum.aspx/coldfusion-server/3206/SQL-Server-2000-Windows-A uth
    Sorry I can't be more clear for you.

  • Don'T repeat item with a LEFT JOIN QUERY

    Hello,
    I would like to know how display the following results:
    *Name*:  John Fox
    *Sales:*  1- LAPTOP
                    2- HARDDRIVE
                    3- COMPUTERHere is my 2 tables: CUSTOMER and SALES
    CUSTOMER
    ID NAME GENDER
    1 John Mayer F
    2 Melissa John F
    3 Julie Black F
    4 Mickael Fox M
    5 John Fox M
    SALES
    ID ID_CUSTOMER TYPE
    1 1 Boat
    2 1 TV
    3 4 CD PLAYER
    4 5 LAPTOP
    5 5 HARDDRIVE
    6 5 COMPUTER
    My QUERY
    SELECT customer.Name as NAME, customer.Gender, sales.TYPE
    from customer
    LEFT JOIN sales
    ON customer.ID = sales.ID_CUSTOMER
    WHERE customer.Name = 'John Fox'The problem: If I use the default template, I have:
    NAME GENDER TYPE
    John Fox M LAPTOP
    John Fox M HARDDRIVE
    John Fox M COMPUTER I don'T want the Name John Fox to be repeated at each row.
    I tried to add: #Name# in the REGION DEFINITION - REGION HEADER but I have this result:
    #NAME#
    NAME GENDER TYPE
    John Fox M LAPTOP
    John Fox M HARDDRIVE
    John Fox M COMPUTER
    So, what can I do to have this result? Change the query???
    Name:  John Fox
    Sales: 1- LAPTOP
           2- HARDDRIVE
            3- COMPUTER               thanks,
         Roseline

    Hi Roseline,
    You can adapt the solution suggested in this post Re: More than 1 records in one cell
    Thanks,
    Manish

  • I need help with SQL query

    Hi All,
    I have a problem in the query below. When I run the query I got a pop-up screen to ente value for
    :total_balance,
    :emp_code,
    :from_date,
    :to_date
    total_balance supose to be a result of a calculation.
    Your assistance is apreciated. Thanks,
    Ribhi
    select      FK_VOUCHERSERIAL_N,
         FK_VOUCHERVALUE_DA,
         DESCRIPTION,
         nvl(AMOUNT,0) amount,
         TYPE,
         Accnt101.postive_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) postive_amount,
         Accnt101.negative_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) negative_amount,
         Accnt101.total_balanceformula(:total_balance, EMPLOYEE_TRANSACTI.TYPE,Accnt101.negative_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) ,Accnt101.postive_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) , nvl(AMOUNT,0)) total_balance
    from      EMPLOYEE_TRANSACTI
    where     FK_EMPLOYEENUMBER0=:emp_code
    and     STATUS=1
    and     FK_VOUCHERVALUE_DA<=:to_date
    and     FK_VOUCHERVALUE_DA>=:from_date
    and     ((TYPE >7 and TYPE <16)
         or (TYPE >34 and TYPE <43)
         or (TYPE =7)
         or (TYPE =18)
         or (TYPE >26 and TYPE <35)
         or (TYPE =17)
         OR (TYPE = 60)
         OR (TYPE = 70)
    OR (TYPE = 72)
    OR (TYPE = 73)
    OR (TYPE = 74)
         or (type = 21)
         or (type =24)
         or (type = 81)
         or (type = 82))
    order by      FK_VOUCHERVALUE_DA asc, FK_VOUCHERSERIAL_N asc, type desc

    Hi Satyaki,
    My problem is with SQL and PL/SQL codd. I managed to convert some of my reports and now I'm facing a problem with converted SQL and PL/SQL code. To give you an Idea the following is a sample of a converted report.
    Pls have a look. (p.s how can i post formated text)
    Thanks,
    Ribhi
    1 - XML template file
    <?xml version="1.0" encoding="UTF-8" ?>
    - <dataTemplate name="Accnt101" defaultPackage="Accnt101" version="1.0">
    - <properties>
    <property name="xml_tag_case" value="upper" />
    </properties>
    - <parameters>
    <parameter name="FROM_DATE" dataType="date" defaultValue="01/01/1998" />
    <parameter name="TO_DATE" dataType="date" defaultValue="31/12/1998" />
    <parameter name="EMP_CODE" dataType="number" defaultValue="44" />
    </parameters>
    <lexicals />
    - <dataQuery>
    - <sqlStatement name="employee_trans">
    - <![CDATA[
    select      FK_VOUCHERSERIAL_N,
         FK_VOUCHERVALUE_DA,
         DESCRIPTION,
         nvl(AMOUNT,0) amount,
         TYPE,
         Accnt101.postive_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) postive_amount,
         Accnt101.negative_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) negative_amount,
         Accnt101.total_balanceformula(:total_balance, EMPLOYEE_TRANSACTI.TYPE,Accnt101.negative_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) ,Accnt101.postive_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) , nvl(AMOUNT,0)) total_balance
    from      EMPLOYEE_TRANSACTI
    where     FK_EMPLOYEENUMBER0=:emp_code
    and     STATUS=1
    and     FK_VOUCHERVALUE_DA<=:to_date
    and     FK_VOUCHERVALUE_DA>=:from_date
    and     ((TYPE >7 and TYPE <16)
         or (TYPE >34 and TYPE <43)
         or (TYPE =7)
         or (TYPE =18)
         or (TYPE >26 and TYPE <35)
         or (TYPE =17)
         OR (TYPE = 60)
         OR (TYPE = 70)
                    OR (TYPE = 72)
                    OR (TYPE = 73)
                    OR (TYPE = 74)
         or (type = 21)
         or (type =24)
         or (type = 81)
         or (type = 82))
    order by      FK_VOUCHERVALUE_DA asc, FK_VOUCHERSERIAL_N asc, type desc
      ]]>
    </sqlStatement>
    - <sqlStatement name="employee">
    - <![CDATA[
    select NAME,NUMBER0
    from EMPLOYEE
    where  NUMBER0=:emp_code
      ]]>
    </sqlStatement>
    </dataQuery>
    <dataTrigger name="beforeReportTrigger" source="Accnt101.beforereport" />
    - <dataStructure>
    - <group name="G_employee_trans" dataType="varchar2" source="employee_trans">
    <element name="FK_VOUCHERSERIAL_N" dataType="number" value="FK_VOUCHERSERIAL_N" />
    <element name="FK_VOUCHERVALUE_DA" dataType="date" value="FK_VOUCHERVALUE_DA" />
    <element name="DESCRIPTION" dataType="varchar2" value="DESCRIPTION" />
    <element name="AMOUNT" dataType="number" value="AMOUNT" />
    <element name="postive_amount" dataType="number" value="postive_amount" />
    <element name="negative_amount" dataType="number" value="negative_amount" />
    <element name="total_balance" dataType="number" value="total_balance" />
    <element name="TYPE" dataType="number" value="TYPE" />
    <element name="CS_1" function="sum" dataType="number" value="G_employee_trans.total_balance" />
    </group>
    - <group name="G_employee" dataType="varchar2" source="employee">
    <element name="NUMBER0" dataType="number" value="NUMBER0" />
    <element name="NAME" dataType="varchar2" value="NAME" />
    </group>
    <element name="balance" dataType="number" value="Accnt101.balance_p" />
    <element name="CS_2" function="count" dataType="number" value="G_employee.NUMBER0" />
    <element name="CS_3" function="count" dataType="number" value="G_employee_trans.AMOUNT" />
    </dataStructure>
    </dataTemplate>
    2 - PLS/SQL package
    CREATE OR REPLACE PACKAGE Accnt101 AS
         from_date     date;
         to_date     date;
         emp_code     number;
         balance     number := 0 ;
         function postive_amountformula(TYPE in number, amount in number) return number ;
         function negative_amountformula(TYPE in number, amount in number) return number ;
         function BeforeReport return boolean ;
         function total_balanceformula(total_balance in number, TYPE in number, negative_amount in number, postive_amount in number, amount in number) return number ;
         Function balance_p return number;
    END Accnt101;
    3- Package Body
    CREATE OR REPLACE PACKAGE BODY Accnt101 AS
    function postive_amountformula(TYPE in number, amount in number) return number is
    begin
         if ((TYPE>26 and TYPE<35)
              or (TYPE=17))
         then
              return(amount);
         elsif (type = 70)and (amount >=0) then
              return (amount) ;
    elsif (type = 72)and (amount >=0) then
              return (amount) ;
    elsif (type = 73)and (amount >=0) then
              return (amount) ;
    elsif (type = 74)and (amount >=0) then
              return (amount) ;
         elsif (type = 60)and (amount >=0) then
              return (amount) ;
         else
              return (null) ;
         end if;
    RETURN NULL; end;
    function negative_amountformula(TYPE in number, amount in number) return number is
    begin
         if ((TYPE>7 and TYPE<16)
              or (TYPE >34 and TYPE <43)
              or (TYPE=7)
              or (TYPE=18)
              or (type=21)
              or (type=24)
              or (type= 81)
              or (type=82))
         then
              return(amount);
         elsif (type = 70)and (amount <0) then
              return (abs (amount)) ;
    elsif (type = 72)and (amount <0) then
              return (abs (amount)) ;
    elsif (type = 73)and (amount <0) then
              return (abs (amount)) ;
    elsif (type = 74)and (amount <0) then
              return (abs (amount)) ;
         elsif (type = 60)and (amount <0) then
              return (abs(amount)) ;
         else
              return (null) ;
         end if;
    RETURN NULL; end;
    function BeforeReport return boolean is
    var_pos     number(15,3) ;
    var_neg     number(15,3) ;
    beg_bal     number(15,3) ;
    Begin
    begin
    select sum (nvl(amount,0)) into beg_bal
         from EMPLOYEE_TRANSACTI
         where (TYPE=99 or type = 92 or type = 93 or type = 94)
         and to_char(from_date,'YYYY')=to_char(date0,'YYYY')
         and FK_EMPLOYEENUMBER0=emp_code;
    EXCEPTION
         WHEN NO_DATA_FOUND THEN
         beg_bal := 0;
    end;
    begin
         select      sum(nvl(amount,0)) into var_pos
         from      EMPLOYEE_TRANSACTI
         where      
              (TYPE=17
              or type=60
              OR TYPE=70
    oR TYPE=72
    OR TYPE=73
    OR TYPE=74
              or (TYPE>26 and TYPE<35))
         and      fk_vouchervalue_da<from_date
         and      fk_vouchervalue_da>= trunc(from_date,'year')
         and      FK_EMPLOYEENUMBER0=emp_code;
    EXCEPTION
         WHEN NO_DATA_FOUND THEN
         var_pos := 0;
    end;
    Begin     
         select sum(nvl(amount,0)) into var_neg
         from EMPLOYEE_TRANSACTI
         where ((TYPE>7 and TYPE<16)
              or (TYPE >34 and TYPE <43)
              or (TYPE=7)
              or (TYPE=18)
              or (type=21)
              or (type=24)
              or (type= 81)
              or (type=82) )
         and fk_vouchervalue_da<from_date
         and fk_vouchervalue_da>= trunc(from_date,'year')
         and FK_EMPLOYEENUMBER0=emp_code;
         balance :=nvl(beg_bal,0) + nvl(var_pos,0) - nvl(var_neg,0);
         return(true);
    EXCEPTION
         WHEN NO_DATA_FOUND THEN
         balance :=nvl(beg_bal,0) + nvl(var_pos,0) - nvl(var_neg,0);
              RETURN (TRUE);
    end;
    RETURN NULL; end;
    function total_balanceformula(total_balance in number, TYPE in number, negative_amount in number, postive_amount in number, amount in number) return number is
    begin
         if total_balance is null then
         if ((TYPE>7 and TYPE<16)
              or (TYPE >34 and TYPE <43)
              or (TYPE=7)or (TYPE=18)
              or (type=21) or (type=24)
              or (type= 81)
              or (type=82))
         then
              return(balance-negative_amount);
         elsif ((TYPE>26 and TYPE<35) or (TYPE=17))
              then
                   return(balance+postive_amount);
              elsif (type=70 or type=72 or type=73 or type=74
    or type=60) and (amount >=0) then
                   return(balance+postive_amount);
              elsif (type=70 or type=72 or type=73 or type=74
    or type=60) and (amount <0) then
                   return(balance-negative_amount);
         end if;
         else
         if ((TYPE>7 and TYPE<16)
              or (TYPE >34 and TYPE <43)
              or (TYPE=7)or (TYPE=18)
              or (type=21) or (type=24)
              or (type= 81)
              or (type=82))
         then
              return(total_balance-negative_amount);
         elsif ((TYPE>26 and TYPE<35) or (TYPE=17))
              then
                   return(total_balance+postive_amount);
              elsif (type=70 or type=72 or type=73 or type=74
    or type=60) and (amount >=0) then
                   return(total_balance+postive_amount);
              elsif (type=70 or type=72 or type=73 or type=74
    or type=60) and (amount <0) then
                   return(total_balance-negative_amount);
         end if;
         end if ;
    RETURN NULL; end;
    Functions to refer Oracle report placeholders
    Function balance_p return number is
         Begin
         return balance;
         END;
    END Accnt101 ;

  • Help with SQL join

    I've got a query where I'm joining several tables. One of the tables (schedule_status) has no rows to match for the join and it's causing no rows to be returned.. What I need for it to happen would be to return a -1 for c_schedulestatusid..
    This is what I have
    select distinct li.location as locationid, li.city, li.state as stateid, li.descr as location,
    s.state, sl.name as mgrname, 'default' as locationtype, c_schedulestatusid
    from location_info li
    left outer join states s on li.state = s.abbreviation
    left outer join mvw_sm_location sl on li.location = sl.location
    left outer join schedule_status ss on li.location = ss.location
    where li.emplid = '0087890'
    and year = 2007
    and week = 11This is the part that returns no data
    select c_schedulestatusid
    from schedule_status
    where year = 2007
    and week = 11
    and location = 4131I've tried using nvl() and a couple other tricks but I can't get it to work... Thanks!

    Maybe it's bacause I don't have real/sample data.
    here is my sample data, states and mvw_sm_location doesn't have any row
    SQL> select * from location_info;
    LOCATION   CITY       STATE      DESCR      EMPLID
    4131                                        0087890
    3376                                        0087890
    SQL> select * from schedule_status;
    C_SCHEDULE       YEAR       WEEK LOCATION
    1                2007          3 3376
    here is the result with location=3376 outside inline query
    SQL> set autotrace on expl
    SQL> select distinct li.location as locationid, li.city,
      2         li.state as stateid, li.descr as location,
      3         s.state, sl.name as mgrname, 'default' as locationtype,
      4         nvl(c_schedulestatusid,-1) c_schedulestatusid
      5  from location_info li
      6       left outer join states s on li.state = s.abbreviation
      7       left outer join mvw_sm_location sl on li.location = sl.location
      8       left outer join ( select location, c_schedulestatusid
      9                         from schedule_status
    10                         where year = 2007
    11                         and week = 3 ) ss
    12       on li.location = ss.location
    13  where li.emplid = '0087890' and li.location = 3376;
    LOCATIONID CITY       STATEID    LOCATION   STATE      MGRNAME    LOCATIO C_SCHEDULE
    3376                                                              default 1
    Execution Plan
    Plan hash value: 115315777
    | Id  | Operation             | Name            | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT      |                 |     1 |    55 |    13  (24)| 00:00:01 |
    |   1 |  HASH UNIQUE          |                 |     1 |    55 |    13  (24)| 00:00:01 |
    |*  2 |   HASH JOIN OUTER     |                 |     1 |    55 |    12  (17)| 00:00:01 |
    |*  3 |    HASH JOIN OUTER    |                 |     1 |    41 |     8  (13)| 00:00:01 |
    |*  4 |     HASH JOIN OUTER   |                 |     1 |    27 |     6  (17)| 00:00:01 |
    |*  5 |      TABLE ACCESS FULL| LOCATION_INFO   |     1 |    13 |     3   (0)| 00:00:01 |
    |   6 |      TABLE ACCESS FULL| STATES          |     1 |    14 |     2   (0)| 00:00:01 |
    |   7 |     TABLE ACCESS FULL | MVW_SM_LOCATION |     1 |    14 |     2   (0)| 00:00:01 |
    |*  8 |    TABLE ACCESS FULL  | SCHEDULE_STATUS |     1 |    14 |     3   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       2 - access("LI"."LOCATION"="LOCATION"(+))
       3 - access("LI"."LOCATION"="SL"."LOCATION"(+))
       4 - access("LI"."STATE"="S"."ABBREVIATION"(+))
       5 - filter("LI"."EMPLID"='0087890' AND TO_NUMBER("LI"."LOCATION")=3376)
       8 - filter("YEAR"(+)=2007 AND "WEEK"(+)=3)
    here is the result with location=3376 inside inline query
    SQL> select distinct li.location as locationid, li.city,
      2         li.state as stateid, li.descr as location,
      3         s.state, sl.name as mgrname, 'default' as locationtype,
      4         nvl(c_schedulestatusid,-1) c_schedulestatusid
      5  from location_info li
      6       left outer join states s on li.state = s.abbreviation
      7       left outer join mvw_sm_location sl on li.location = sl.location
      8       left outer join ( select location, c_schedulestatusid
      9                         from schedule_status
    10                         where year = 2007
    11                         and week = 3
    12                         and location = 3376 ) ss
    13       on li.location = ss.location
    14  where li.emplid = '0087890' ;
    LOCATIONID CITY       STATEID    LOCATION   STATE      MGRNAME    LOCATIO C_SCHEDULE
    3376                                                              default 1
    4131                                                              default -1
    Execution Plan
    Plan hash value: 115315777
    | Id  | Operation             | Name            | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT      |                 |     1 |    55 |    13  (24)| 00:00:01 |
    |   1 |  HASH UNIQUE          |                 |     1 |    55 |    13  (24)| 00:00:01 |
    |*  2 |   HASH JOIN OUTER     |                 |     2 |   110 |    12  (17)| 00:00:01 |
    |*  3 |    HASH JOIN OUTER    |                 |     2 |    82 |     8  (13)| 00:00:01 |
    |*  4 |     HASH JOIN OUTER   |                 |     2 |    54 |     6  (17)| 00:00:01 |
    |*  5 |      TABLE ACCESS FULL| LOCATION_INFO   |     2 |    26 |     3   (0)| 00:00:01 |
    |   6 |      TABLE ACCESS FULL| STATES          |     1 |    14 |     2   (0)| 00:00:01 |
    |   7 |     TABLE ACCESS FULL | MVW_SM_LOCATION |     1 |    14 |     2   (0)| 00:00:01 |
    |*  8 |    TABLE ACCESS FULL  | SCHEDULE_STATUS |     1 |    14 |     3   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       2 - access("LI"."LOCATION"="LOCATION"(+))
       3 - access("LI"."LOCATION"="SL"."LOCATION"(+))
       4 - access("LI"."STATE"="S"."ABBREVIATION"(+))
       5 - filter("LI"."EMPLID"='0087890')
       8 - filter("YEAR"(+)=2007 AND "WEEK"(+)=3 AND TO_NUMBER("LOCATION"(+))=3376)
    Your last query give the same result but with more costly execution plan
    SQL> select *
      2  from (
      3     select to_char(a.location) locationid,
      4                 a.c_schedulestatusid + nvl(b.c_schedulestatusid,0) as c_schedulestatusid
      5     from
      6     (
      7             select distinct to_char(location) location, -1 as c_schedulestatusid
      8             from location_info
      9     ) a
    10     full outer join
    11     (
    12             select location, c_schedulestatusid + 1 as c_schedulestatusid
    13             from schedule_status
    14             where week = 3
    15             and year = 2007
    16     ) b
    17     on b.location = a.location
    18  ) status
    19  right outer join
    20  (
    21     select distinct li.location as locationid, li.city,
    22                 li.state as stateid, li.descr as location,
    23            s.state, sl.name as mgrname
    24     from location_info li
    25     left outer join states s on li.state = s.abbreviation
    26     left outer join mvw_sm_location sl on li.location = sl.location
    27     where emplid = '0087890'
    28  ) locations
    29  on locations.locationid = status.locationid;
    LOCATIONID C_SCHEDULESTATUSID LOCATIONID CITY       STATEID    LOCATION   STATE      MGRNAME
    3376                        1 3376
    4131                       -1 4131
    Execution Plan
    Plan hash value: 2617725192
    | Id  | Operation               | Name            | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT        |                 |     2 |   130 |    24  (21)| 00:00:01 |
    |*  1 |  HASH JOIN OUTER        |                 |     2 |   130 |    24  (21)| 00:00:01 |
    |   2 |   VIEW                  |                 |     1 |    42 |     9  (23)| 00:00:01 |
    |   3 |    HASH UNIQUE          |                 |     1 |    41 |     9  (23)| 00:00:01 |
    |*  4 |     HASH JOIN OUTER     |                 |     2 |    82 |     8  (13)| 00:00:01 |
    |*  5 |      HASH JOIN OUTER    |                 |     2 |    54 |     6  (17)| 00:00:01 |
    |*  6 |       TABLE ACCESS FULL | LOCATION_INFO   |     2 |    26 |     3   (0)| 00:00:01 |
    |   7 |       TABLE ACCESS FULL | STATES          |     1 |    14 |     2   (0)| 00:00:01 |
    |   8 |      TABLE ACCESS FULL  | MVW_SM_LOCATION |     1 |    14 |     2   (0)| 00:00:01 |
    |   9 |   VIEW                  |                 |     3 |    69 |    14  (15)| 00:00:01 |
    |  10 |    UNION-ALL            |                 |       |       |            |          |
    |  11 |     VIEW                |                 |     2 |    34 |     8  (25)| 00:00:01 |
    |  12 |      HASH UNIQUE        |                 |     2 |    54 |     8  (25)| 00:00:01 |
    |* 13 |       HASH JOIN OUTER   |                 |     2 |    54 |     7  (15)| 00:00:01 |
    |  14 |        TABLE ACCESS FULL| LOCATION_INFO   |     2 |    26 |     3   (0)| 00:00:01 |
    |* 15 |        TABLE ACCESS FULL| SCHEDULE_STATUS |     1 |    14 |     3   (0)| 00:00:01 |
    |* 16 |     HASH JOIN ANTI      |                 |     1 |    19 |     7  (15)| 00:00:01 |
    |* 17 |      TABLE ACCESS FULL  | SCHEDULE_STATUS |     1 |    14 |     3   (0)| 00:00:01 |
    |  18 |      TABLE ACCESS FULL  | LOCATION_INFO   |     2 |    10 |     3   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       1 - access("LOCATIONS"."LOCATIONID"=INTERNAL_FUNCTION("A"."LOCATION"(+)))
       4 - access("LI"."LOCATION"="SL"."LOCATION"(+))
       5 - access("LI"."STATE"="S"."ABBREVIATION"(+))
       6 - filter("LI"."EMPLID"='0087890')
      13 - access("LOCATION"(+)=INTERNAL_FUNCTION("LOCATION"))
      15 - filter("WEEK"(+)=3 AND "YEAR"(+)=2007)
      16 - access("LOCATION"=INTERNAL_FUNCTION("LOCATION"))
      17 - filter("WEEK"=3 AND "YEAR"=2007)Cheers,
    NH.

Maybe you are looking for

  • ERROR on Receivables Manager - receipt

    Hi Updating transaction in Recevables manager save doesnt work due to error of APP-AR-96024: Account generator is unable to derive infomation for one or more of the following accounts: COA-50328; Orig CCID:; SUB CCID: 6537 i found a solution The Crea

  • PI Scenarios

    Following are the links to weblogs which will help to develop the basic scenarios. Introduction to IDoc-XI-File scenario and complete walk through for starters. - IDoc to File ABAP Proxies in XI(Client Proxy) - ABAP Proxy to File FILE to JDBC Adapter

  • Slow XSQL Servlet - any seetings that might improve the performance?

    Hi, I am using: - oracle 10g - XSQL 10.1.0.2.0 I am using the XSQLServlet to generate web pages(xsql + xsl). For a certain sql execution it takes about 20 seconds(for 70 records retrieved from a table of 2,5 million records). The exact same query exe

  • FF tabbar does not appear even though the option is checked.

    I just got a new hard drive and installed FF 12 and transferred my profile. My profile was from FF 11 and I just hadn't gotten around to updating. My profile and everything works fine so far, but every time I start FF the tabbar is not there. I must

  • Trying to upgrade to Ap. 2 but it wont accept my Aperture 1 Serial No.

    Trying to install my aperture 2 upgrade software but it rejects my original aperture 1 serial number. Any ideas why this is happening?