Duplicates in sql query out put when qury has join on multiple tables.

I have the below query whcih is returning 2 duplicate records.
Is there any way how to figure out from which table is causing the duplicate?
There are so many inline view and join conditions in this query .
in waht join conditions i need to look into mainly?
or how to find the whcih table is causing the duplicate when we have multimple joins?
this is really bothering me a lot .please help me with this.
SELECT       'BCCALGLB'            model_cd,
                     fi_instrument_id,
                     fmr_cusip             instrument_id,
                     price,
                     '27-FEB-2013'          pricing_dt,
                     currency_cd
                     FROM         (SELECT  II.fmr_cusip,
                              IAI.fi_instrument_id,
                              IP.price,
                              IP.currency_cd
                      FROM    (SELECT  IdxHldg.vendor_instrument_id,
                                       IdxHldg.index_cd,
                                       IdxHldg.data_source_cd,
                                       GM.member_rank,
                                       RANK () OVER (PARTITION BY  IdxHldg.vendor_instrument_id
                                                     ORDER BY      GM.member_rank  ASC)  priority
                               FROM    (SELECT  IBH.vendor_instrument_id,
                                                IBH.index_cd,
                                                IBH.data_source_cd
                                        FROM    fi_idx_benchmark_holdings  IBH
                                        WHERE   IBH.pricing_dt = '27-FEB-2013'
                                        UNION
                                        SELECT  IFH.vendor_instrument_id,
                                                IFH.index_cd,
                                                IFH.data_source_cd
                                        FROM    fi_idx_forward_holdings  IFH
                                        WHERE   IFH.pricing_dt = '27-FEB-2013'
                                       )  IdxHldg,
                                       fi_group_member  GM
                               WHERE   GM.group_cd      = 'BCGLOBALIDX'
                               AND     GM.purpose_cd    = 'GLOBALIDX'
                               AND     IdxHldg.index_cd = GM.character_val
                              )  BCIdxHldg,
                              fi_idx_instrument  II,
                              fi_idx_price  IP,
                              instrument_alternate_id  IAI,
                              instrument  I
                      WHERE   BCIdxHldg.priority                  =      1
                      AND     BCIdxHldg.data_source_cd            =      II.data_source_cd
                      AND     BCIdxHldg.vendor_instrument_id      =      II.vendor_instrument_id
                      AND     II.data_source_cd                   =      IP.data_source_cd
                      AND     II.vendor_instrument_id             =      IP.vendor_instrument_id
                      AND     IP.currency_cd                      =      I.currency_cd
                      AND     IP.pricing_dt                       =      '27-FEB-2013'
                      AND     II.fmr_cusip                        =      IAI.alternate_id
                      AND     IAI.alternate_id_type_code          =      'FMR_CUSIP'
                      AND     IAI.fi_instrument_id                =      I.fi_instrument_id
                      AND     NVL (I.instrument_domain_cd, 'XXX') NOT IN ('MBS', 'MGEN')
                      AND     NVL (I.instrument_type_cd, 'XXX')   !=     'CMBS'
                      AND     ((I.currency_cd                     NOT IN ('CAD', 'USD'))
                               OR
                               (EXISTS (SELECT  1
                                        FROM    adm_calendar_date  ACD,
                                                ctry_curr_link  CCL
                                        WHERE   TO_DATE (ACD.calendar_yyyymmdd, 'YYYYMMDD') = '27-FEB-2013'
                                        AND     ACD.calendar_origin_cd                      = 'EXCHANGE'
                                        AND     ACD.calendar_type_cd                        = 'BUSINESS'
                                        AND     ACD.geography_cd                            = CCL.ctry_cd
                                        AND     CCL.link_typ                                = 'ISS'
                                        AND     CCL.curr_cd                                 = I.currency_cd
                                        AND     ACD.business_day_ind                        = 'Y'))))

Hi,
953115 wrote:
I have the below query whcih is returning 2 duplicate records.
Is there any way how to figure out from which table is causing the duplicate?
There are so many inline view and join conditions in this query .
in waht join conditions i need to look into mainly?
or how to find the whcih table is causing the duplicate when we have multimple joins?What has changed since the last time the query ran correctly? (It must have run correctly at some point. You didn't just write a query that big all at once without testing each individual part, did you?)
Find a small set of sample data that causes the problem. Create and work with tables that have only that small set of data.
Take baby steps. Start with the most deeply nested sub-query. and simplify it so that it uses only 1 table: comment out all references to other tables. Does it produce exactly what you're expecting, especially the number of rows?
If not, post just that one sub-query, your sample data, and the output you need (but are not getting) from that sub-query.
If it does work, then un-comment the other tables, 1 at a time. Test after each one. If the revised sub-query starts acting strangely, then you have a good clue about what's causing the problem, but if you can't figure it out, post that much of the query, your sample data (CREATE TABLE and INSERT statements) and the expected results from the code you posted.
If then entire sub-query works, then add the next super-query, and repeat the testing process.
What is the data type of ibh.pricing_dt?
If its a DATE, then don't compare it to a VARCHAR2, as you're doing in this line:
IBH.pricing_dt = '27-FEB-2013'Use TO_DATE to convert a string, such as '27-FEB-2013', to a DATE.
If it's not a DATE (or TIMESTAMP), then you have an even more serious problem.

Similar Messages

  • Oracle outer join on  multiple tables throws error

    Hi ,
    We are using ansi joins with outer joins on multiple tables in oracle 9i.
    Now these queries have to be used in Oracle8i.
    Since Oracle8i does not support ansi sql we are replacing the ansi sql queries with the oracle joins.
    On trying the same we found that the following query
    select *from tab1 a, tab2 b, tab3 c where a.c1 = b.col1(+) and c.c2 = b.col2 (+)
    throws the error
    ORA-01417: a table may be outer joined to at most one other table.
    Is there a way to simulate this query without using the outer joins on multiple tables?
    thanks

    Try writing the query in this form:
    select * from
    (select t1.col1, t1.col2
    from schema.table1 t1, schema.table2 t2
    where t1.col1 = t2.col1(+)) t4,
    schema.table3 t3 where t4.col2 = t3.col2(+)
    In the subquery, you will have to list all the columns you want to see, and you will need to provide unique aliases for any columns with duplicate names. I tested this on 9i, and don't have an 8i system to work with, so I hope this helps.

  • Left outer join using multiple table

    Hi,
    I am trying to use left outer join with multiple tables , the join condition will be based on  PERNR and BEGDA & ENDA for each infotype in selection screen.
      select pa00~pernr pa00~begda pa00~endda pa00~massn pa00~massg pa00~stat2 pa00~aedtm pa00~uname
        pa01~begda pa01~endda pa01~bukrs pa01~persg pa01~persk pa01~mstbr pa01~ename pa01~aedtm pa01~uname
        pa02~begda pa02~endda pa02~nachn pa02~vorna pa02~midnm pa02~aedtm pa02~uname
        pa016~begda pa016~endda pa016~cttyp pa016~aedtm pa016~uname
        into CORRESPONDING FIELDS OF TABLE i_pall
        from  ( PA0000 as pa00 left OUTER JOIN pa0001 as pa01 on pa00~pernr = pa01~pernr )
        left OUTER JOIN pa0002 as pa02 on pa00~pernr eq pa02~pernr )
        left OUTER JOIN  pa0016 as pa016 on pa00~pernr eq pa016~pernr )
        where pa00~pernr in S_pernr
        AND pa00~begda in s_bg0000
        and pa00~endda in s_nd0000.
    but this fails  to fetch the value of begda enda from each pa0000,pa0001,pa0002,pa0016.
    Please help!
    Monirul

    Why don't you use the standard logical database PNPCE and then Provide statement?

  • Query Out Put

    Hi All,
      I generated query the out put of query is as shown below.
    ma01        10kg   dc01
    ma02        20kg   dc02
    I dont want kg in the second column but I want only numbers like 10,20...
      Thanx in advance.

    Hi,
    Use NODIM function for your mass.
    Best regards,
    Eugene

  • QBE style(Find-Execute) Query not executing when VO has bind parameter

    I have an Entity Based ViewObject that is composed of 3 Entities so the entities are related through an Assoc. Then the ViewObject also has a bind paremeter defined and used in the WHERE clause.
    In my page everything is fine until when I use/click on the Find operation on the JSF page. When the Find operation is executed the page/form goes blank so I can enter by QBE query. Now when I Execute my search by executing the ExecuteWith params operation. Nothing is happening to the screen, it seems that query was not executed. Although there was no errors or exceptions displayed.
    However if I remove the bind parameter, and execute the Execute operation instead after going to Find mode, the query is executed properly and I get expected results.
    My problem is a bit general, but are there anyone who had a similar problem like this? Im still in the process of creating a test case.
    regards,
    Anton

    Hi Frank,
    But the "ExecuteWithParams" operation provides the bind variable right? (i had the value hardcoded on the pagedef). So it must have supplied a value. I also noticed that this is happening only when if the VIewObject contains two or more Entities. If the Viewobject has only 1 entity, the ViewObject queries properly.
    Anyway Frank, I had found a fix for this. I set an InvokeAction on the pagedef that binds to the ExecuteWithParams that is invoked during page load only(!postback condition). and then I just use the Find-Execute operations instead of the Find-ExecuteWithParams operations that I used previously.
    I will try to replicate the issue again to investigate what's really going on. I just want to know if its a bug or just an expected behavior or i just made a mistake.
    regards,
    Anton

  • SQL Query to put end date to user account from Backend.

    We are using Oracle Apps 11.5.10.2. with oracle 9i Database.
    I want to put end date to user account who has left a week ago, (Responsibility ->Sysadmin - Go to : User)
    i cannot give the enddate as sysdate, i need to put the end date (25-JUN-09) from back end.
    I want a query so that the workflow tables also get updated accordingly.
    Regards,
    Jenny

    Yes i can give the back dated end date, but when i check the record history from Front end,
    (Help ---> Record History) These details are not updated , they will show the Updated By : username and Updated Date to sysdate and not the back dated date given.

  • Document currency in cube but not in the getting in query out put

    Hi Gurus,
    I am in production.... my query is regarding account receivable( which is user defined ie., is custom )  i am able to see amount in document currency in cube but is not appering when i excute the query ...
    And i am to get the output amount in local currency ( i am getting ) amount in document ( not getting )
    and revalution amount ( not getting )---- which is cal key fig 
    and finally   Amount FAS ( not getting ) ---  which is Restricted key fig
    Gurus Please suggest ..........

    Hi,
    The fields in the report
    customer
    HFC code
    doc Number
    business divison
    sales order
    country
    profit center
    customer number compounded with company code
    customer payment terms
    reference
    documennt type
    document date
    net due date
    G/L Account comp cpde
    item  Status
    Document currency
    Account in Local currency
    Amount  in Document currency
    filters are
    compay code
    controling area
    Business Division
    Free char
    Controling area
    account type
    clearing Doc Number
    Ref Key 2
    Fical year
    Fiscal year / period
    interunit / outside
    Posting Date
    Leading BD ( Wbs Attr)
    in rows
    customer
    doc number
    business divison
    sales order
    country
    profit center
    customer bumber compounded with company code
        under this we have customer payment terms
    Reference
    document type
    document date
    Net due date
    G/L Account Comp code
    item status
    Document Currency
    In columns
    i am selecting
    Amount  in local currency
    amount Document currency
    Revaluation amount
    Amount in FAS

  • SQL Query to find when the data was committed

    Hi,
    In oracle how do we find the when the row as committed into DB(Timestamp):
    Eg:
    If insert 1000 records from the application i want to know what is exact time the data was committed in the DB.
    Regards
    NM

    NM wrote:
    Hi,
    Thanks for your Input.
    The Query returned the following.But I want something like this 7/6/2011 6:43:54.23:32:00000 PM(Includes micro seconds)
    SELECT ora_rowscn,orderid FROM tibex_order  where orderid='0NEC.000OXNVE9JYSNQC' ;
    12541143230,0NEC.000OXNVE9JYSNQC
    SELECT SCN_TO_TIMESTAMP(ORA_ROWSCN) FROM tibex_order where orderid='0NEC.000OXNVE9JYSNQC' ;
    7/6/2011 6:43:54.000000000 PMRegards
    NMIt's already giving it to you in nano-seconds.
    What's with this format:???
    But I want something like this 7/6/2011 6:43:54.23:32:00000 PM
                                            ^ ^  ^  ^^^
                                            | |  |  ||+-- what is this colon for?
                                            | |  |  |+--- hundredths of seconds
                                            | |  |  +---- tenths of seconds
                                            | |  +------- seconds
                                            | +---------- minutes 
                                            +------------ hour

  • Total result  & formula result  is wrong in query out put

    Hi BW gurus
    I have issue with total result and formula result
    my requirement
    Formula for hours is ( total time / Counter / 60)
    hours  column displaying
       14.2
         2.4
         3.4
    Total -
    5.6   not  20    then I setp calculate results to SUM  now total displying 20  perfect.
    Then I am using hours colum for calculation   here is my issue
    Qty rec per hour formula is = received / Hour
    Hours   Qty rec per hour          received
    14.2              100                            14200
    2..4               100                              2400
    3.4                100                              3400
    20                 300                              20000        result column for qty rec per hour is wrong . formula is not working on result for qty rec per hour
    Actually qty rec per hour result should be 20000/20  = 1000
    How to resolve this issue
    Thanks
    Rohan

    Hi BW Gurus,
    Thanks for your help .
    Let me explain my issue with examples :
    My report is by document date level ( Not at Po or PO line Level)
    I have a 3 Key figures
    1.  Hour -  is poulation at  PO Line level
    Ex :  4500001    1             5.30
                             2            5.30
                             3            5.30
    Then I am using counter to get single for time
    Hour/ Count  now my value is 5.30 in the report . hour column is perfect
    2. Po Qty  is fine
    3.  Qty Recd per hour ( Calculation)    PO QTy / Hour
    Now the issue is  each row caluculating perfect . but result row is not correct  Qty Received per hour . We don"t wont  sum of  Qty received per hour in result . We want  Caluclation result in the result
    Here is the issue
    If I have multiple POs for same document date  , each row is fine but system using division at Hour result also by COunter . because of thati am getting wrong hours in result for hour . this wrong result is using for Poqty receved per hour result  also .
    I put total for hour coulum result is perfect but for clauclation it is talking total hours/ total conter result .How to replace result caluculating by counter .This is our major issue .
    Appriciate your response
    Thanks
    Rohan

  • In the query out put,right click on k.f,there we fine one option HIDE

    why we use it?

    hi,
        it is generally used if you do not want to see the keyfigure in the query output.
    if u wnat to do analysis on sales and you do notyt want to see predouction kf then u can use it
    regards
    pls assign points if helful.

  • Changing the Infoset Query out put field

    Hi,
      Please let me know can we do the changes for the Input/Output field for the infoset query in PRD. That mean  if some of the fields are hidden and we want to show them at the output can we directly do the changes in PRD .
    Thanks & Best Regards,
      Mahesh

    hi
    Create the infoset with PNP database and add all the infotypes required (including custom ones). Add all fields.. vale, text etc. as seperate fields of the custom Z tables as additional fields in the infotypes and write your code accordingly to select the data into these fields based on the already existing infotype fields. For example if you want to get designation based on position you will write:
    select <designation> from ZDESG
    into <custom field>
    where PLANS = P0001-PLANS
    Creating joins over already existing joins will not be a stable solution.
    thanks & regards
    Satish

  • SQL Query to calculate on-time dispatch with a calendar table

    Hi Guys,
    I have a query (view) to calculate orders' fulfillment leadtimes.
    The current criteria exclude week-ends but not bank holidays therefore I have created a calendar table with a column name
    isBusinessDay but I don't know how to best use this table to calculate the On-Time metric. I have been looking everywhere but so far I have been unable to solve my problem.
    Please find below the current calculation for the On-Time Column:
    SELECT
    Week#
    , ClntGroup
    , CORD_DocumentCode
    , DESP_DocumentCode
    , Cord_Lines --#lines ordered
    , CORD_Qty --total units orderd
    , DESP_Lines --#lines dispatched
    , DESP_Qty --total units dispatched
    , Status
    , d_status
    , OpenDate --order open date
    , DateDue
    , DESP_PostedDate --order dispatched date
    , DocType
    , [Lead times1]
    , [Lead times2]
    , InFxO
    , OnTime
    , InFxO + OnTime AS InFullAndOneTime
    , SLADue
    FROM (
    SELECT
    DATEPART(WEEK, d.DateOpn) AS Week#
    , Clients.CustCateg
    , Clients.ClntGroup
    , d.DocumentCode AS CORD_DocumentCode
    , CDSPDocs.DocumentCode AS DESP_DocumentCode
    , COUNT(CORDLines.Qnty) AS Cord_Lines
    , SUM(CORDLines.Qnty) AS CORD_Qty
    , COUNT(CDSPLines.Qnty) AS DESP_Lines
    , SUM(CDSPLines.Qnty) AS DESP_Qty
    , CDSPLines.Status
    , d.Status AS d_status
    , d.OpenDate
    , d.DateDue
    , CDSPDocs.PostDate AS DESP_PostedDate
    , d.DocType
    , DATEDIFF(DAY, d.OpenDate, d.DateDue) AS [Lead times1]
    , DATEDIFF(DAY, d.OpenDate, CDSPDocs.PostDate) AS [Lead times2]
    , CASE WHEN SUM(CORDLines.Qnty) = SUM(CDSPLines.Qnty) THEN 1 ELSE 0 END AS InFxO --in-full
    --On-Time by order according to Despatch SLAs
    , CASE
    WHEN Clients.ClntGroup IN ('Local Market', 'Web Sales', 'Mail Order')
    AND (DATEDIFF(DAY, d.OpenDate, CDSPDocs.PostDate) - (DATEDIFF(WEEK, d.OpenDate, CDSPDocs.PostDate) * 2 ) <= 2)
    THEN 1
    WHEN Clients.ClntGroup IN ('Export Market', 'Export Market - USA')
    AND (DATEDIFF(DAY, d.OpenDate, CDSPDocs.PostDate) - (DATEDIFF(WEEK, d.OpenDate, CDSPDocs.PostDate) * 2) <= 14)
    THEN 1
    WHEN Clients.ClntGroup = 'Export Market' OR Clients.CustCateg = 'UK Transfer'
    AND d.DateDue >= CDSPDocs.PostDate
    THEN 1
    ELSE 0
    END AS OnTime
    --SLA Due (as a control)
    , CASE
    WHEN Clients.ClntGroup IN ('Local Market', 'Web Sales','Mail Order') AND CDSPDocs.PostDate is Null
    THEN DATEADD(DAY, 2 , d.OpenDate)
    WHEN Clients.ClntGroup IN ('Export Market', 'Export Market - UK', 'Export Market - USA') OR (Clients.CustCateg = 'UK Transfer')
    AND CDSPDocs.PostDate IS NULL
    THEN DATEADD (DAY, 14 , d.OpenDate)
    ELSE CDSPDocs.PostDate
    END AS SLADue
    FROM dbo.Documents AS d
    INNER JOIN dbo.Clients
    ON d.ObjectID = dbo.Clients.ClntID
    AND Clients.ClientName NOT in ('Samples - Free / Give-aways')
    LEFT OUTER JOIN dbo.DocumentsLines AS CORDLines
    ON d.DocID = CORDLines.DocID
    AND CORDLines.TrnType = 'L'
    LEFT OUTER JOIN dbo.DocumentsLines AS CDSPLines
    ON CORDLines.TranID = CDSPLines.SourceID
    AND CDSPLines.TrnType = 'L'
    AND (CDSPLines.Status = 'Posted' OR CDSPLines.Status = 'Closed')
    LEFT OUTER JOIN dbo.Documents AS CDSPDocs
    ON CDSPLines.DocID = CDSPDocs.DocID
    LEFT OUTER JOIN DimDate
    ON dimdate.[Date] = d.OpenDate
    WHERE
    d.DocType IN ('CASW', 'CORD', 'MORD')
    AND CORDLines.LneType NOT IN ('Fght', 'MANF', 'Stor','PACK', 'EXPS')
    AND CORDLines.LneType IS NOT NULL
    AND d.DateDue <= CONVERT(date, GETDATE(), 101)
    GROUP BY
    d.DateOpn
    ,d.DocumentCode
    ,Clients.CustCateg
    ,CDSPDocs.DocumentCode
    ,d.Status
    ,d.DocType
    ,d.OpenDate
    ,d.DateReq
    ,CDSPDocs.PostDate
    ,CDSPLines.Status
    ,Clients.ClntGroup
    ,d.DocumentName
    ,d.DateDue
    ,d.DateOpn
    ) AS derived_table
    Please find below the DimDate table
    FullDateNZ HolidayNZ IsHolidayNZ IsBusinessDay
    24/12/2014 NULL 0 1
    25/12/2014 Christmas Day 1 0
    26/12/2014 Boxing Day 1 0
    27/12/2014 NULL 0 0
    28/12/2014 NULL 0 0
    29/12/2014 NULL 0 1
    30/12/2014 NULL 0 1
    31/12/2014 NULL 0 1
    1/01/2015 New Year's Day 1 0
    2/01/2015 Day after New Year's 1 0
    3/01/2015 NULL 0 0
    4/01/2015 NULL 0 0
    5/01/2015 NULL 0 1
    6/01/2015 NULL 0 1
    This is what I get from the query:
    Week# ClntGroup CORD_DocumentCode OpenDate DESP_PostedDate OnTime
    52 Web Sales 123456 24/12/2014 29/12/2014 0
    52 Web Sales 123457 24/12/2014 30/12/2014 0
    52 Web Sales 123458 24/12/2014 29/12/2014 0
    52 Local Market 123459 24/12/2014 29/12/2014 0
    1 Web Sale 123460 31/12/2014 5/01/2015 0
    1 Local Market 123461 31/12/2014 6/01/2015 0
    As the difference between the dispatched and open date is 2 business days or less, the result I expect is this:
    Week# ClntGroup CORD_DocumentCode OpenDate DESP_PostedDate OnTime
    52 Web Sales 123456 24/12/2014 29/12/2014 1
    52 Web Sales 123457 24/12/2014 30/12/2014 1
    52 Web Sales 123458 24/12/2014 29/12/2014 1
    52 Local Market 123459 24/12/2014 29/12/2014 1
    1 Web Sale 123460 31/12/2014 5/01/2015 1
    1 Local Market 123461 31/12/2014 6/01/2015 1
    I am using SQL Server 2012
    Thanks
    Eric

    >> The current criteria exclude week-ends but not bank holidays therefore I have created a calendar table with a column name “isBusinessDay” but I don't know how to best use this table to calculate the On-Time metric. <<
    The Julian business day is a good trick. Number the days from whenever your calendar starts and repeat a number for a weekend or company holiday.
    CREATE TABLE Calendar
    (cal__date date NOT NULL PRIMARY KEY, 
     julian_business_nbr INTEGER NOT NULL, 
    INSERT INTO Calendar 
    VALUES ('2007-04-05', 42), 
     ('2007-04-06', 43), -- good Friday 
     ('2007-04-07', 43), 
     ('2007-04-08', 43), -- Easter Sunday 
     ('2007-04-09', 44), 
     ('2007-04-10', 45); --Tuesday
    To compute the business days from Thursday of this week to next
     Tuesdays:
    SELECT (C2.julian_business_nbr - C1.julian_business_nbr)
     FROM Calendar AS C1, Calendar AS C2
     WHERE C1.cal__date = '2007-04-05',
     AND C2.cal__date = '2007-04-10'; 
    We do not use flags in SQL; that was assembly language. I see from your code that you are still in a 1960's mindset. You used camelCase for a column name! It makes the eyes jump and screws up maintaining code; read the literature. 
    The “#” is illegal in ANSI/ISO Standard SQL and most other ISO Standards. You are writing 1970's Sybase dialect SQL! The rest of the code is a mess. 
    The one column per line, flush left and leading comma layout tells me you used punch cards when you were learning programming; me too! We did wrote that crap because a card had only 80 columns and uppercase only IBM 027 character sets. STOP IT, it make you
    look stupid in 2015. 
    You should follow ISO-11179 rules for naming data elements. You failed. You believe that “status” is a precise, context independent data element name! NO! 
    You should follow ISO-8601 rules for displaying temporal data. But you used a horrible local dialect. WHY?? The “yyyy-mm-dd” is the only format in ANSI/ISO Standard SQL. And it is one of the most common standards embedded in ISO standards. Then you used crap
    like “6/01/2015” which is varying length and ambiguous that might be “2015-06-01” or “2015-01-06” as well as not using dashes. 
    We need to know the data types, keys and constraints on the table. Avoid dialect in favor of ANSI/ISO Standard SQL. 
    And you need to read and download the PDF for: 
    https://www.simple-talk.com/books/sql-books/119-sql-code-smells/
    >> Please find below the current calculation for the On-Time Column: <<
    “No matter how far you have gone down the wrong road, turn around”
     -- Turkish proverb
    Can you throw out this mess and start over? If you do not, then be ready to have performance got to hell? You will have no maintainable code that has to be kludged like you are doing now? In a good schema an OUTER JOIN is rare, but you have more of them in
    ONE statement than I have seen in entire major corporation databases.
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • SQL query  update to the Effective Dated Row in PS_JOB table?  SQL Server

    Hi,
    I have a requirement to update the Holiday Schedule field in the maximum effective date row based on the criteria: EMPL_RCD and BUSINESS_UNIT.
    Initially I ran a select query to see how many rows will gets affected.It fetched rows properly with the criteria.
    When I am trying to update the query with the same criteria its showing error message.
    But I don't find any mistake in my query...
    Here is the query I have used:
    UPDATE PS_JOB J SET J.HOLIDAY_SCHEDULE='HLDY' WHERE
    J.EFFDT=(SELECT MAX(A.EFFDT) FROM PS_JOB A
    WHERE A.EMPLID=J.EMPLID
    AND A.EMPL_RCD=J.EMPL_RCD
    AND A.EFFDT<=GETDATE())
    AND J.EFFSEQ=
    (SELECT MAX(A1.EFFSEQ) FROM PS_JOB A1
    WHERE A1.EMPLID=J.EMPLID
    AND A1.EMPL_RCD=J.EMPL_RCD
    AND A1.EFFDT=J.EFFDT)
    AND J.BUSINESS_UNIT='HLDY1'
    AND J.EMPL_RCD=0
    Try with differnt ways but no result. Could anyone please guide me how I can update it....
    Thanks in Advance!

    My database is MY SQL server.
    I found the issue and it is working now. Update syntax works diffrently when we use alias name in set column.
    UPDATE PS_JOB SET HOLIDAY_SCHEDULE='HLDY' FROM PS_JOB J WHERE
    J.EFFDT=(SELECT MAX(A.EFFDT) FROM PS_JOB A
    WHERE A.EMPLID=J.EMPLID
    AND A.EMPL_RCD=J.EMPL_RCD
    AND A.EFFDT<=GETDATE())
    AND J.EFFSEQ=
    (SELECT MAX(A1.EFFSEQ) FROM PS_JOB A1
    WHERE A1.EMPLID=J.EMPLID
    AND A1.EMPL_RCD=J.EMPL_RCD
    AND A1.EFFDT=J.EFFDT)
    AND J.BUSINESS_UNIT='HLDY1'
    AND J.EMPL_RCD=0
    This has worked in SQL server.
    Thanks for looking into this.

  • SQL - Select Help - Case When? Return Value from Second Table?

    Hi - next to folks on this board I am probably somewhere between a Beginner and an Intermediate SQL user.
    Ive been using a case when statement in plsql to find "all those who's status in any program was cancelled during a specific time, but have become or are still active in a second program"
    So, Im effectively trying to return a value from a second table in a case when, but its not liking anthing other than a declared text like 'Yes' or 'No'.
    Here is the select statement - is there another way to do this where I can get the results I need?
    case when pp.party_id in (select pp1.party_id  -- Cancelled clients Active in another program
                                       from asa.program_participation          pp1,
                                            asa.curr_prog_participation_status cpps1
                                      where pp1.program_participation_id = cpps1.program_participation_id
                                        and pp1.party_id = pp.party_id
                                        and cpps1.code_value = 'ACT')
                then 'Yes' else 'No' end  as Active_in_Other_Prg
    So - in place of 'Yes' i basically want the program that they are active in or pp1.program_id, else Null
    It is possible that the client can be active in more than one program as well.
    Any assistance is greatly appreciated, i explored with if's and decodes but I cant get anything to work.
    Batesey

    Sounds like an outer join. See ora doc: Joins
    select p.*
    ,      q.party_id
    ,      q.program_id
    from   table_with_party_id p
    ,    ( select pp1.party_id  -- Cancelled clients Active in another program
           ,      pp1.program_id
           from   asa.program_participation          pp1,
                  asa.curr_prog_participation_status cpps1
           where  pp1.program_participation_id = cpps1.program_participation_id
           and    pp1.party_id = pp.party_id
           and    cpps1.code_value = 'ACT') q
    where p.party_id = q.party_id ( +)
    Note: In the example above there shoudn't be a space between the ( and +), but the forum software automagically converts this to
    The outer join will link show all records from the p table and only records from q if the party_id matches, ie q.party_id and q.program_id  will be null if there is no match.
    edit: added program_id

  • SQL query problem:  how tp select all duplication in the table?

    Hi all,
    I have a table with the following columns:
    1. contact_id
    2. fname
    3. lname
    4. email
    The email column must be unique (unfortunately it's not); therefore, I have to delete all duplication in the system.
    Question: how can I select all duplication in the table?
    I tried this...didn't work (I'm expecting only the emails that are duplicated)
    THANK YOU!
    SELECT distinct TC1.email, TC1.contact_ID FROM ta_contacts AS TC1 where TC1.email <>'' AND TC1.email not in (   SELECT distinct TC2.email   FROM ta_contacts AS TC2   where TC2.email <>'' )

    Sounds like an SQL and not a JDBC question. In any case, if a column needs to be unique, then you should, of course, designate a unique constraint on the table so you never end up with duplicates in the first place.

Maybe you are looking for

  • Passing the values in Recipe  PLM WEBUI

    Created a new tab for Recipe via customization in PLM Web UI. But I am not able to  create new fields in the screen and pass the values. Please let me know the configuration steps and how to pass the values to PLM Web UI

  • HyperLink in Email Task for Workflow

    Hi experts, I need to place a Hyperlink in an email task in my work flow(e.g. <A HREF="URL">Name</A>).  When I do this it looks and acts correctly in SOST but when it is sent to outlook it is not a Hyperlink but the actual text. Is there a way to do

  • How reliable is S.M.A.R.T. Status?

    Hello, I had a talk with a guy from the Genius Bar yesterday and he seem to have lots of knowledge on disk drives and failures. He told me, the SMART check in disk utillity is very accurate, because it reads the hard disk SMART data. I have a dying W

  • G/L Account hits for Production Planning (Process Industry)

    Dear Experts,   Please I want to know the G/L Acounts that will be hit/updated during a Process order execution cycle enumerated as follows; RawMaterials: R09 & R19,  SemiFinished: S24,  Finished: F29 Each of the three material types above has a diff

  • PS CC can't open any files

    I  have PS CC installed on two devices, and on one of them it keeps telling me that it's a 30 days trial (I pay on an annual basis) and it wants me to write a code, which I haven't got. - that's the one thing, and the other is that it won't open any